对于VC++对话框而言,有时候我们希望当我们在键盘敲下某个按键时,程序能进入某个响应事件入口,执行我们希望的操作。这就需要我们先获取按键消息,并根据消息结构体MSG的参数判断敲下的是那个按键,并响应它。当我们按下某按键时,系统会默认调用CWnd类的成员函数PreTranslateMessage()做出某些处理。例如当按下回车键或者退出键时,默认执行CDialog::OnOk()函数,导致对话框窗口关闭,但这并不是我们希望的结果。有时候我们到希望设置热键:当按下回车或某个个按键时,程序执行某个事件。这就需要我们先获取到按键事件,然后转到我们需要执行的程序入口。
我们先看看CWnd类的成员函数PreTranslateMessage(),其原型为:
virtual BOOL PreTranslateMessage( MSG* pMsg );参数MSG*pMsg表示系统获取到的消息结构体,我们再看看这个结构体的成员变量(摘自MSDN):
This structure contains message information from a thread message queue.
typedef struct tagMSG { HWND hwnd; UINT message; WPARAM wParam; LPARAM lParam; DWORD time; POINT pt; } MSG, *PMSG, *NPMSG, *LPMSG;
Members
- hwnd
- Identifies the window whose window procedure receives the message.
- message
- Specifies the message number.
- wParam
- Specifies additional information about the message. The exact meaning depends on the value of the message member.
- lParam
- Specifies additional information about the message. The exact meaning depends on the value of the message member.
- time
- Specifies the time at which the message was posted.
- pt
- Specifies the cursor position, in screen coordinates, when the message was posted.
怎么获得按键事件呢?
1、右键你的对话框类,选择“Add virtual Function”或从ClassWizard重载父类CWnd类的虚函数PreTranslateMessage;
2、对该函数重新定义。
比如我要重定义对话框对回车键和退出键的消息响应事件
BOOL CNetBrgSetParamDlg::PreTranslateMessage(MSG* pMsg) { if (pMsg->message == WM_KEYDOWN && (pMsg->wParam == VK_ESCAPE || pMsg->wParam==VK_RETURN)) { DoSomeThingYouWant(para1,……); } return CDialog::PreTranslateMessage(pMsg); }