做完棋盘之后却无法完成左键点击棋盘,而切换棋盘BMP图片

做完棋盘之后却无法完成左键点击棋盘,而切换棋盘BMP图片

解决办法:
目前推测可能是因为HDC的原因造成无法切换,HDC只能在WM_PAINT消息中使用,其它消息中使用都不会被执行。
有了原因就想出对策,把需要HDC的函数全部放在WM_PAINT消息中去处理,这样就可以共用WM_PAINT中的HDC了

代码:
 
     
  1. HINSTANCE g_hInst = NULL;
  2. HANDLE g_hStdout = NULL; //控制台
  3. CHAR szText[256] = { 0 }; //调试用
  4. #define PrintLog(x) WriteConsole(g_hStdout, x, strlen(x), 0, 0);
  5. int i = 1;
  6. //获得坐标
  7. int xPos = 0;
  8. int yPos = 0;
  9. void DrawBk(HDC hDC)
  10. {
  11. int marc = 0; //控制棋盘所在位置
  12. for (int i = 0; i < 10; i++) //画九格横线
  13. {
  14. MoveToEx(hDC, marc + 50, marc + 50 + i * 48, NULL);
  15. LineTo(hDC, marc + 480, marc + 50 + i * 48);
  16. }
  17. for (int j = 0; j < 10; j++) //画九格直线
  18. {
  19. MoveToEx(hDC, marc + 50 + j * 48, marc + 50, NULL);
  20. LineTo(hDC, marc + 50 + j * 48, marc + 480);
  21. }
  22. //背景图处理
  23. HBITMAP hBitMap = LoadBitmap(g_hInst, MAKEINTRESOURCE(IDB_BKMP1));
  24. HDC hBmap = CreateCompatibleDC(hDC);
  25. HGDIOBJ hOldBmp = SelectObject(hBmap, hBitMap);
  26. //绘图开始
  27. for (int i = 0; i < 9; i++)
  28. {
  29. for (int j = 0; j < 9; j++)
  30. {
  31. BitBlt(hDC, 50 + j * 48, 50 + i * 48, 48, 48, hBmap, 0, 0, MERGECOPY);
  32. }
  33. }
  34. SelectObject(hDC, hOldBmp);
  35. DeleteDC(hBmap);
  36. DeleteObject(hBitMap);
  37. }
  38. void OnLButton(HDC hDC)
  39. {
  40. //PAINTSTRUCT ps = { 0 };
  41. //HDC hDC = BeginPaint(hWnd, &ps);
  42. int marc = 0; //控制棋盘所在位置
  43. if (xPos>50 && yPos >50)
  44. {
  45. //背景图处理
  46. HBITMAP hBitMap = LoadBitmap(g_hInst, MAKEINTRESOURCE(IDB_BKMP2));
  47. HDC hBmap = CreateCompatibleDC(hDC);
  48. HGDIOBJ hOldBmp = SelectObject(hBmap, hBitMap);
  49. //绘图开始
  50. int xPoint = (xPos - 50) / 48;
  51. int yPoint = (yPos - 50) / 48;
  52. sprintf_s(szText, 256, "OnLButton,x=%d,y=%d\n", xPoint, yPoint);
  53. PrintLog(szText);
  54. BitBlt(hDC, 50 + xPoint * 48, 50 + yPoint * 48, 48, 48, hBmap, 0, 0, SRCCOPY);
  55. SelectObject(hDC, hOldBmp);
  56. DeleteDC(hBmap);
  57. DeleteObject(hBitMap);
  58. }
  59. }
  60. //OnPaint
  61. void OnPaint(HWND hWnd, UINT nMsg, WPARAM wParam, LPARAM lParam)
  62. {
  63. PAINTSTRUCT ps = { 0 };
  64. HDC hDC = BeginPaint(hWnd, &ps);
  65. if (i == 1) //暂时屏蔽棋盘每次刷新的办法,后面可以用控件解决
  66. {
  67. DrawBk(hDC);
  68. i = 2;
  69. }
  70. OnLButton(hDC);
  71. EndPaint(hWnd, &ps);
  72. }



来自为知笔记(Wiz)


转载于:https://www.cnblogs.com/nfking/p/5573147.html

你可能感兴趣的:(做完棋盘之后却无法完成左键点击棋盘,而切换棋盘BMP图片)