为什么OnKeyDown不会在基于对话框的MFC项目中捕获关键事件? [英] Why doesn't OnKeyDown catch key events in a dialog-based MFC project?
问题描述
我只是在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
这篇关于为什么OnKeyDown不会在基于对话框的MFC项目中捕获关键事件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!