方式一:重载PreTranslateMessage()
在类向导的虚函数中增加PreTranslateMessage()
注意:如果处理WM_KEYDOWN消息,按键在按下不抬起的情况下,每隔一段时间就会触发一次,如果只想要触发一次,请使用WM_KEYUP
BOOL CTest::PreTranslateMessage(MSG* pMsg)
{
// TODO: 在此添加专用代码和/或调用基类
if (pMsg->message == WM_KEYUP)
{
switch (pMsg->wParam)
{
case VK_UP:
printf("WM_KEYUP UP\n"); break;
case VK_DOWN:
printf("WM_KEYUP DOWN\n"); break;
case VK_LEFT:
printf("WM_KEYUP LEFT\n"); break;
case VK_RIGHT:
printf("WM_KEYUP RIGHT\n"); break;
case VK_PRIOR:
printf("WM_KEYUP PgUp\n"); break;
case VK_NEXT:
printf("WM_KEYUP PgDn\n"); break;
default:
break;
}
}
if (pMsg->message == WM_KEYDOWN)
{
switch (pMsg->wParam)
{
case VK_UP:
printf("WM_KEYDOWN UP\n"); break;
case VK_DOWN:
printf("WM_KEYDOWN DOWN\n"); break;
case VK_LEFT:
printf("WM_KEYDOWN LEFT\n"); break;
case VK_RIGHT:
printf("WM_KEYDOWN RIGHT\n"); break;
case VK_PRIOR:
printf("WM_KEYDOWN PgUp\n"); break;
case VK_NEXT:
printf("WM_KEYDOWN PgDn\n"); break;
default:
break;
}
}
return CDialogEx::PreTranslateMessage(pMsg);
}
方式二:注册热键 + 重载OnHotKey()
1、在OnInitDialog()函数中增加代码块
BOOL CTest::OnInitDialog()
{
...
...
// TODO: 在此添加额外的初始化代码
RegisterHotKey(m_hWnd, 1, NULL, VK_UP);
RegisterHotKey(m_hWnd, 2, NULL, VK_DOWN);
RegisterHotKey(m_hWnd, 3, NULL, VK_LEFT);
RegisterHotKey(m_hWnd, 4, NULL, VK_RIGHT);
RegisterHotKey(m_hWnd, 5, NULL, VK_PRIOR);
RegisterHotKey(m_hWnd, 6, NULL, VK_NEXT);
return TRUE; // 除非将焦点设置到控件,否则返回 TRUE
}
2、在类向导中增加消息OnHotKey()
void CKeyboardDlg::OnHotKey(UINT nHotKeyId, UINT nKey1, UINT nKey2)
{
// TODO: 在此添加消息处理程序代码和/或调用默认值
switch (nHotKeyId)
{
case 1:
PostMessage(WM_COMMAND, MAKEWPARAM(IDC_BUTTON_UP, BN_CLICKED), NULL);
break;
case 2:
PostMessage(WM_COMMAND, MAKEWPARAM(IDC_BUTTON4_DOWN, BN_CLICKED), NULL);
break;
case 3:
PostMessage(WM_COMMAND, MAKEWPARAM(IDC_BUTTON_LEFT, BN_CLICKED), NULL);
break;
case 4:
PostMessage(WM_COMMAND, MAKEWPARAM(IDC_BUTTON_RIGHT, BN_CLICKED), NULL);
break;
case 5:
PostMessage(WM_COMMAND, MAKEWPARAM(IDC_BUTTON_PgUp, BN_CLICKED), NULL);
break;
case 6:
PostMessage(WM_COMMAND, MAKEWPARAM(IDC_BUTTON8_PgDn, BN_CLICKED), NULL);
break;
default:
break;
}
CDialogEx::OnHotKey(nHotKeyId, nKey1, nKey2);
}