为什么 OnKeyDown 不捕获基于对话框的 MFC 项目中的关键事件?
我只是在 MFC (VS2008) 中创建了一个基于对话框的项目并将 OnKeyDown
事件添加到对话框中.当我运行项目并按下键盘上的键时,没有任何反应.但是,如果我从对话框中删除所有控件并重新运行项目,它就可以工作.即使对话框上有控件,我应该怎么做才能获取关键事件?
I just create a dialog-based project in MFC (VS2008) and add OnKeyDown
event to the dialog.
When I run the project and press the keys on the keyboard, nothing happens. But, if I remove all the controls from the dialog and rerun the project it works.
What should I do to get key events even when I have controls on the dialog?
这是一段代码:
void CgDlg::OnKeyDown(UINT nChar, UINT nRepCnt, UINT nFlags)
{
// TODO: Add your message handler code here and/or call default
AfxMessageBox(L"Key down!");
CDialog::OnKeyDown(nChar, nRepCnt, nFlags);
}
推荐答案
当对话框上有控件时,对话框本身永远不会获得焦点.它被儿童控件偷走了.当您按下一个按钮时,一个 WM_KEYDOWN
消息将发送到具有焦点的控件,因此您的 CgDlg::OnKeyDown
永远不会被调用.如果您希望对话框处理 WM_KEYDOWN
消息,请覆盖对话框的 PreTranslateMessage
函数:
When a dialog has controls on it, the dialog itself never gets the focus. It's stolen by the child controls. When you press a button, a WM_KEYDOWN
message is sent to the control with focus so your CgDlg::OnKeyDown
is never called. Override the dialog's PreTranslateMessage
function if you want dialog to handle the WM_KEYDOWN
message:
BOOL CgDlg::PreTranslateMessage(MSG* pMsg)
{
if(pMsg->message == WM_KEYDOWN )
{
if(pMsg->wParam == VK_DOWN)
{
...
}
else if(pMsg->wParam == ...)
{
...
}
...
else
{
...
}
}
return CDialog::PreTranslateMessage(pMsg);
}
另请参阅 CodeProject 上的这篇文章:http://www.codeproject.com/KB/dialog/pretransdialog01.aspx
Also see this article on CodeProject: http://www.codeproject.com/KB/dialog/pretransdialog01.aspx
相关文章