How to prevent dialog from closing on Enter/Escape in MFC

Implicit behaviour of dialogs in MFC is, that the dialog closes when user presses <Enter> (equivalent to pressing “OK” button) or <Escape> (“Cancel” button).

To prevent this, you have to override dialog class’ PreTranslateMessage() function, and use the following code to “translate” the <Enter> and <Escape> keys to <Tab> key:

BOOL CMyDialog::PreTranslateMessage(MSG* pMsg)
{
    if (pMsg->message == WM_KEYDOWN)
    {
        if ((pMsg->wParam == VK_RETURN) || (pMsg->wParam == VK_ESCAPE))
            pMsg->wParam = VK_TAB;
    }
    return CDialog::PreTranslateMessage(pMsg);
}

13 responses to “How to prevent dialog from closing on Enter/Escape in MFC

  1. Thank you again. I’ve been programming for years and I always forget that I have to do this.
    Is it possible to make it translate to “no character”, rather than the ersatz TAB ?

  2. I’m out of the MFC waters for quite some time now, so I’m not sure how can you translate to “no character” (I’m sure there is a way, but can’t remember).

    But one thought that comes to my mind is, that you could map these to any key that is not actually being mapped by the dialog (e.g. to VK_CONTROL – <Ctrl> key); this would result in its equivalent – “no action”.

    Please, let us know if you find an option for “no key”.

  3. Pingback: Enter dialog | Seininha

  4. Or a simple solution can be, override IDCANCEL and IDOK command ids

    ON_COMMAND(IDOK, OnOk)
    ON_COMMAND(IDCANCEL, OnCancel)

    //Disable OnCancel
    void MyDialog::OnCancel()
    {
    }

    //Disable OnOK
    void MyDialog::OnOK()
    {
    }

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s