编写程序: 设计一个窗口, 当单击鼠标左键时, 窗口中显示"LEFT BUTTON"; 当单击鼠标右键时, 窗口中显示"RIGHT BUTTON"; 当单击向上箭头键时, 窗口中显示"UP Key"; 当单击Ctrl键时, 窗口中显示"CTRL Key"; 当单击 Ctrl+A 键时, 窗口中显示"CTRL+A Key": 程序主要代码如下: LRESULT CALLBACK WndProc(HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam) { int wmId, wmEvent; PAINTSTRUCT ps; HDC hDC; //TCHAR szHello[MAX_LOADSTRING]; //LoadString(hInst, IDS_HELLO, szHello, MAX_LOADSTRING); static char cLEFT[]="LEFT BUTTON"; static char cRIGHT[]="RIGHT BUTTON"; static char cUp[]="UP key"; static char cCTRL[]="CTRL key"; static char cCTRLA[]="CTRL+A key"; static BOOL nUpKeyDown=FALSE, nCtrlKeyDown=FALSE, nCtrlAKeyDown=FALSE,nLeftDown=FALSE,nRightDown=FALSE; int xOrg,yOrg; switch (message) { case WM_KEYDOWN: { switch(wParam) { case VK_UP: nUpKeyDown=TRUE; break; case VK_CONTROL: nCtrlKeyDown=TRUE; break;
default: break; } } break;
case WM_KEYUP: InvalidateRect(hWnd,NULL,TRUE); //刷新用户区。 break; case WM_CHAR: { if(wParam==(65&VK_CONTROL)) { if(nCtrlKeyDown == TRUE) { nCtrlAKeyDown = TRUE; nCtrlKeyDown = FALSE; } }
} break; case WM_LBUTTONDOWN: nLeftDown=TRUE; InvalidateRect(hWnd,NULL,TRUE); //刷新用户区。 break; case WM_RBUTTONDOWN: nRightDown=TRUE; InvalidateRect(hWnd,NULL,TRUE); //刷新用户区。 break;
case WM_COMMAND: wmId = LOWORD(wParam); wmEvent = HIWORD(wParam); // Parse the menu selections: switch (wmId) { case IDM_ABOUT: DialogBox(hInst, (LPCTSTR)IDD_ABOUTBOX, hWnd, (DLGPROC)About); break; case IDM_EXIT: DestroyWindow(hWnd); break; default: return DefWindowProc(hWnd, message, wParam, lParam); } break; case WM_PAINT: hDC = BeginPaint(hWnd, &ps); // TODO: Add any drawing code here... RECT rt; GetClientRect(hWnd, &rt); xOrg=(rt.left+rt.right)/2; yOrg=(rt.top +rt.bottom)/2; if(nUpKeyDown == TRUE) { TextOut(hDC,xOrg,yOrg,cUp,strlen(cUp)); nUpKeyDown = FALSE; |
(续前表) } else if(nCtrlAKeyDown == TRUE) { TextOut(hDC,xOrg,yOrg,cCTRLA,strlen(cCTRLA)); nCtrlAKeyDown = FALSE; nCtrlKeyDown = FALSE; } else if(nCtrlKeyDown == TRUE&&nCtrlAKeyDown == FALSE) { TextOut(hDC,xOrg,yOrg,cCTRL,strlen(cCTRL)); nCtrlKeyDown = FALSE; } else if(nLeftDown == TRUE) { TextOut(hDC,xOrg,yOrg,cLEFT,strlen(cLEFT)); nLeftDown = FALSE; } else if(nRightDown == TRUE) { TextOut(hDC,xOrg,yOrg,cRIGHT,strlen(cRIGHT)); nRightDown = FALSE; }
//DrawText(hdc, lpString, _tcsclen(lpString), &rt, DT_CENTER); EndPaint(hWnd, &ps); break; case WM_DESTROY: PostQuitMessage(0); break; default: return DefWindowProc(hWnd, message, wParam, lParam); } return 0; }
编译并调试程序 |
程序运行结果运行结果如下图:
单击鼠标左键
单击鼠标右键
单击向上箭头
单击Ctrl键
单击Ctrl+A 刚开始刷新客户区时使用 InvalidateRect(hWnd,NULL,FALSE); 结果导致背景客户区背景不更新,输出的文本重叠,了解了InvalidateRect()的使用方式后,将语句改为 InvalidateRect(hWnd,NULL,TRUE); 即成功解决了问题; |
转载于:https://www.cnblogs.com/leftshine/p/5698617.html