开发者

Why doesn't OnKeyDown catch key events in a dialog-based MFC project?

开发者 https://www.devze.com 2023-02-05 01:16 出处:网络
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 control

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?

Here's a piece of code:

void CgDlg::OnKeyDown(UINT nChar, UINT nRepCn开发者_高级运维t, UINT nFlags)
{
    // TODO: Add your message handler code here and/or call default
    AfxMessageBox(L"Key down!");
    CDialog::OnKeyDown(nChar, nRepCnt, nFlags);
}


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);  
}

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


Many of my CDialog apps use OnKeyDown(). As long you only want to receive key presses and draw on the screen (as in make a game), delete the default buttons and static text (the CDialog must be empty) and OnKeyDown() will start working. Once controls are placed on the CDialog, OnKeyDown() will no longer be called.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号