
How to prevent dialog from closing on Enter/Escape in MFC
February 29, 2008Implicit 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);
}