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

Simple Add-On Wait Dialog in MFC

Despite the prediction of fast end of MFC due to release of .NET framework, it seems MFC is not about to leave us anytime soon. Personally, in many cases, I prefer it to .NET.

Some time ago I found this jewel I’d like to share with you. The original article has been posted by Jeff Prosise, in Microsoft Systems Journal, February 1997 – Vol 12 No 2, article Wicked Code.
If you wanna know about all the magic hidden behind the code, read the article.

Unfortunately, the article is not any much clear about how to make it all work, so I decided to write this.

Continue reading