locked
OnKeyDown not called when pressing arrow keys RRS feed

  • Question

  • I'm making an MFC Dialog Based Application.

    There are no controls add in the dialog so things are really simple. I just want the dialog to respond when pressing A S D W and arrow keys so that I can move in four directions. However, OnKeyDown is not called when I press arrow keys.

    I've tried OnKeyUp and OnSysKeyDown and they work well.

    Also, I've searched for this problem on the Internet and understand that it is because arrow keys are used to navigate focus among controls and will not call OnKeyDown by default. However, I haven't found a solution.

    Can anyone please tell me how to deal with it? It would be better if you provide sample codes. Thanks!

    -----

    My codes:

    void CGameDlg::OnKeyDown(UINT nChar, UINT nRepCnt, UINT nFlags)
    {
     switch(nChar)
     {
     case 'A':
     case VK_LEFT:
      // Move left
      break;
     case 'S':
     case VK_DOWN:
      // Move down
      break;
     case 'D':
     case VK_RIGHT:
      // Move right
      break;
     case 'W':
     case VK_UP:
      // Move up
      break;
     }
     CDialogEx::OnKeyDown(nChar, nRepCnt, nFlags);
    }
    • Edited by Michael_Kim Tuesday, June 26, 2012 11:13 AM
    Tuesday, June 26, 2012 2:39 AM

Answers

  • You must also handle the message WM_GETDLGCODE. Dialog based applications are special and you need to "enable" specific keys since this keys are used to change the focus of the controls placed on your dialog.

    UINT <Yourdialog>::OnGetDlgCode()
    {
      return DLGC_WANTALLKEYS;
      //return CDialog::OnGetDlgCode();
    }

    • Marked as answer by Michael_Kim Tuesday, June 26, 2012 5:41 AM
    Tuesday, June 26, 2012 5:01 AM

All replies

  • You must also handle the message WM_GETDLGCODE. Dialog based applications are special and you need to "enable" specific keys since this keys are used to change the focus of the controls placed on your dialog.

    UINT <Yourdialog>::OnGetDlgCode()
    {
      return DLGC_WANTALLKEYS;
      //return CDialog::OnGetDlgCode();
    }

    • Marked as answer by Michael_Kim Tuesday, June 26, 2012 5:41 AM
    Tuesday, June 26, 2012 5:01 AM
  • It works well! Thanks!
    Tuesday, June 26, 2012 5:41 AM