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 项目中的关键事件?
基础教程推荐
- c++ STL设置差异 2022-01-01
- 为什么我们不能使用“虚拟继承"?在 COM 中? 2022-01-01
- 如何部分禁用 cmake C/C++ 自定义编译器检查 2021-01-01
- 提升 ASIO 流缓冲 2021-01-01
- 如何在 C++ 中正确使用命名空间? 2022-01-01
- C++:获取传递给函数的多维数组的行大小 2021-01-01
- 随机插入/删除的综合向量与链表基准 2022-01-01
- 与 CAS 的原子交换(使用 gcc 同步内置函数) 2022-01-01
- 将不可复制的闭包对象传递给 std::function 参数 2021-01-01
- 如何更改 SysDateTimePick32 或 CDateTimeCtrl 的背景颜色? 2022-01-01
