Windows – Let the MFC dialog receive keystroke events before its controls (MFC/Win32 equivalent of WinForms “KeyPreview”)

dialogmfcwinapiwindows

I have an MFC dialog containing a dozen or so buttons, radio buttons and readonly edit controls.

I'd like to know when the user hits Ctrl+V in that dialog, regardless of which control has the focus.

If this were C#, I could set the KeyPreview proprety and my form would receive all the keystrokes before the individual controls – but how do I do that in my MFC dialog?

Best Answer

JTeagle is right. You should override PreTranslateMessage().

// Example
BOOL CDlgFoo::PreTranslateMessage( MSG* pMsg )
{
  // Add your specialized code here and/or call the base class
  if ( pMsg->message == WM_KEYDOWN && pMsg->wParam == VK_RETURN )
  {
    int idCtrl= this->GetFocus()->GetDlgCtrlID();
    if ( idCtrl == IDC_MY_EDIT ) {
      // do something <--------------------
      return TRUE; // eat the message
    }
  }

  return CDialog::PreTranslateMessage( pMsg );
}
Related Topic