Why doesn#39;t OnKeyDown catch key events in a dialog-based MFC project?(为什么 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
这篇关于为什么 OnKeyDown 不捕获基于对话框的 MFC 项目中的关键事件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:为什么 OnKeyDown 不捕获基于对话框的 MFC 项目中的关键事件?
基础教程推荐
- GDB 显示调用堆栈上函数地址的当前编译二进制文 2022-09-05
- CString 到 char* 2021-01-01
- 为什么 typeid.name() 使用 GCC 返回奇怪的字符以及如 2022-09-16
- 初始化列表*参数*评估顺序 2021-01-01
- 通过引用传递 C++ 迭代器有什么问题? 2022-01-01
- 为什么派生模板类不能访问基模板类的标识符? 2021-01-01
- 我应该对 C++ 中的成员变量和函数参数使用相同的名称吗? 2021-01-01
- 非静态 const 成员,不能使用默认赋值运算符 2022-10-09
- 为什么 RegOpenKeyEx() 在 Vista 64 位上返回错误代码 2021-01-01
- 如果我为无符号变量分配负值会发生什么? 2022-01-01
