CodeGuru Home VC++ / MFC / C++ .NET / C# Visual Basic VB Forums Developer.com
Results 1 to 1 of 1
  1. #1
    Join Date
    Dec 2001

    MFC Dialog: How to disable/change the behaviour of the <...> key in a dialog?

    Q: How to disable/change the behaviour of the <...> key in a dialog?

    A: There are several ways of doing it:

    • The easiest way is to simply open the resource editor and set the 'Default button' property of the button which should act as the default one.

    • The correct way of diasabling the <Enter> key in MFC is presented in Paul DiLascias' MSDN C++ Q/A Article Enabling Menus in MFC Apps, Changing the Behavior of Enter with DLGKEYS Sample App.. It boils down to processing the 'DM_GETDEFID' message to return 'DC_HASDEFID' in the high word:

      BEGIN_MESSAGE_MAP(CMyDialog, CDialog)
      LRESULT CMyDialog::OnGetDefID(WPARAM wp, LPARAM lp) 
        return MAKELONG(0,DC_HASDEFID); 
      The article also discusses how to change the behaviour of <Enter> and other keys, providing a sample application with source code. Please refer to the article for details.

    • Another workaround can be achieved by overriding 'OnOK()':

      void CYourDialog::OnOK(void)
        CWnd* pWnd = GetFocus();
        if(GetDlgItem(IDOK) == pWnd)
        // Enter key was hit -> do whatever you want
      This solution is a quick-fix, because it lacks on generality.

    • Another 'hack' that seems to be very popular (but not recommendable) is overriding 'PreTranslateMessage()':

      BOOL CYourDialog::PreTranslateMessage(MSG* pMsg)
        // ENTER key
        if((pMsg->message == WM_KEYDOWN) && 
           (pMsg->wParam == VK_RETURN))
          // Enter key was hit -> do whatever you want
          return TRUE;
        return CDialog::PreTranslateMessage(pMsg);
      This is a 'hack' because it breaks the modularity of MFC. If you want to change the behaviour of more keys but just <Enter> you will end up with a labyrinth of 'if' statements in the overriden 'PreTranslateMessage()' function. This is ugly, hard to read, hard to maintain and error prone. The MFC way of doing it is presented in detail in DiLascias' Article.

    For further information on the whole topic, take also a look at the article 'Processing Keyboard Messages ' written by Sam Hobbs.

    Last edited by Andreas Masur; July 24th, 2005 at 04:31 PM.

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts

Windows Mobile Development Center

Click Here to Expand Forum to Full Width

On-Demand Webinars (sponsored)