Why doesn't OnKeyDown capture key events in the MFC dialog project?

I just create an interactive project in MFC (VS2008) and add OnKeyDown to the dialog. When I start the project and press the keys on the keyboard, nothing happens. But, if I remove all the controls from the dialog and restart the project, it will work. What should I do to receive key events, even if I have controls in a dialog box?

Here is the code snippet:

 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); } 
+4
source share
2 answers

When there are controls in a dialog box, the dialog itself never focuses. He is stolen by children's control. When you click the button, the WM_KEYDOWN message is sent to the control with focus, so your CgDlg::OnKeyDown never called. Override the PreTranslateMessage dialog function if you want the dialog to process 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); } 

Also see this article in CodeProject: http://www.codeproject.com/KB/dialog/pretransdialog01.aspx

+16
source

Many of my CDialog apps use OnKeyDown (). As long as you want to receive keystrokes and draw on the screen (as in the game), delete the standard buttons and static text (CDialog should be empty), and OnKeyDown () will start working. When controls are placed on CDialog, OnKeyDown () will no longer be called.

0
source

Source: https://habr.com/ru/post/1335648/


All Articles