对话框如何添加鼠标和键盘响应

1、添加鼠标响应:

在对话框类属性的“重写”中添加WM_MOUSEMOVE/WM_LBUTTONUP/WM_LBUTTONDOWN/WM_LBUTTONDBLCLK消息响应函数

 1 void C窗口响应鼠标消息Dlg::OnLButtonDown(UINT nFlags, CPoint point)
 2 {
 3     MessageBox(_T("鼠标左键按下!"));
 4     CDialogEx::OnLButtonDown(nFlags, point);
 5 }
 6 
 7 void C窗口响应鼠标消息Dlg::OnLButtonDblClk(UINT nFlags, CPoint point)
 8 {
 9     MessageBox(_T("鼠标左键双击!"));
10     CDialogEx::OnLButtonDblClk(nFlags, point);
11 }
12 
13 
14 void C窗口响应鼠标消息Dlg::OnLButtonUp(UINT nFlags, CPoint point)
15 {
16     MessageBox(_T("鼠标左键弹起!"));
17     CString szStr;
18     szStr.Format(_T("X=%d,Y=%d"), point.x, point.y);
19     MessageBox(szStr);
20     CDialogEx::OnLButtonUp(nFlags, point);
21 }
22 
23 void C窗口响应鼠标消息Dlg::OnMouseMove(UINT nFlags, CPoint point)
24 {
25     MessageBox(_T("鼠标在移动!"));
26     CDialogEx::OnMouseMove(nFlags, point);
27 }

 2、添加键盘响应:

 1 BOOL C窗口响应键盘消息Dlg::PreTranslateMessage(MSG* pMsg)
 2 {
 3     if (pMsg->message == WM_KEYDOWN) {
 4         switch (pMsg->wParam) {
 5         case VK_CONTROL:
 6             MessageBox(_T("按下了Ctrl"));
 7             break;
 8         case VK_DOWN:
 9             MessageBox(_T("按下了向下键"));
10             break;
11         case VK_UP:
12             MessageBox(_T("按下了向上键"));
13             break;
14         case VK_LEFT:
15             MessageBox(_T("按下了向左键"));
16             break;
17         case VK_RIGHT:
18             MessageBox(_T("按下了向右键"));
19             break;
20         default:
21             MessageBox(_T("按下了键"));
22             break;
23         }
24     }
25     return CDialogEx::PreTranslateMessage(pMsg);
26 }

你可能感兴趣的:(对话框如何添加鼠标和键盘响应)