How to Trap WM_KEYDOWN Messages in a CDialogID: Q117563
|
Certain Windows messages are difficult to trap in a dialog box because they are either processed by the Windows internal dialog procedure or sent to the control instead of the dialog box. There are several ways to do this, but they usually involve subclassing all the controls in the dialog box or using a Windows hook function. The method described in this article uses the predefined overridable MFC hook function ProcessMessageFilter() to capture these messages. The idea is to override the MFC preinstalled hook function, ProcessMessageFilter(), to trap the messages before they get to the dialog box.
The following steps are the required to implement the hook function. The
SCRIBBLE sample was used as the base for the steps. In Visual C++ 32-bit
Edition, version 4.0, use SCRIBBLE sample STEP3.
In this example, the steps outlined below trap WM_KEYDOWN for a specific
dialog box:
SCRIBBLE.H
<Inside CScribbleApp class>
public:
HWND m_hwndDialog;
SCRIBBLE.CPP
<Inside CScribbleApp::InitInstance>
m_hwndDialog = NULL;
NOTE: Because this message filter applies to the entire application,
there may be a performance hit when you use this method.
SCRIBBLE.H
public:
virtual BOOL ProcessMessageFilter(int code, LPMSG lpMsg);
SCRIBBLE.CPP
BOOL CScribbleApp::ProcessMessageFilter(int code, LPMSG lpMsg)
{
// Check to make sure CPenWidthsDlg is up
if (m_hwndDialog != NULL)
{
if ((lpMsg->hwnd == m_hwndDialog) ||
::IsChild(m_hwndDialog, lpMsg->hwnd))
// Use ::IsChild to get messages that may be going
// to the dialog's controls. In the case of
// WM_KEYDOWN this is required.
{
if (lpMsg->message == WM_KEYDOWN)
TRACE("Got WM_KEYDOWN\n");
}
}
// Default processing of the message.
return CWinApp::ProcessMessageFilter(code, lpMsg);
}
For more information on overriding ProcessMessageFilter, please see
the MFC online Help.
PENDLG.H
protected:
virtual BOOL OnInitDialog();
afx_msg void OnDestroy();
PENDLG.CPP
<Add to Message Map>
ON_WM_DESTROY()
BOOL CPenWidthsDlg::OnInitDialog()
{
CDialog::OnInitDialog();
// Use AfxGetApp() to get pointer to CWinApp-derived
// object; then cast the pointer to our type and assign
((CScribbleApp *)AfxGetApp())->m_hwndDialog = m_hWnd;
return TRUE; // Return TRUE
// unless you set the focus to a control.
}
void CPenWidthsDlg::OnDestroy()
{
CDialog::OnDestroy();
// Use AfxGetApp() to get pointer to CWinApp-derived
// object; then cast the pointer to our type and assign
((CScribbleApp *)AfxGetApp())->m_hwndDialog = NULL;
}
Q72219 Context-Sensitive Help in a Dialog Box Through F1This article explains how to set a hook function for a specific dialog and how to remove the hook after the dialog box has terminated. That method requires more Windows programming knowledge.
Additional query words: kbinf 1.00 1.50 2.00 2.10 2.50 3.00 3.10 4.00 key keystroke
Keywords : kbnokeyword kbMFC kbVC
Version : 1.00 1.50 1.51 1.52 | 1.00 2.00
Platform : NT WINDOWS
Issue type :
Last Reviewed: July 21, 1999