Handling Enter and Escape from Modal Dialogs
Windows only

Problem

The problem is simple: how to stop my MFC modal dialog box from closing when the user presses the Enter or Escape keys?

Solution

The first step is to, on your CDialog-drived class, override the CWnd::PreTranslateMessage virtual function. This function is used translate window messages before they are dispatched to the TranslateMessage and DispatchMessage Windows functions. Then, add the following block of code:

BOOL CMyModalDialog::PreTranslateMessage( MSG* pMsg )
{
  if( pMsg )
  {
    if( pMsg->message == WM_KEYDOWN )
    {
      if( pMsg->wParam == VK_RETURN | pMsg->wParam == VK_ESCAPE )
        pMsg->wParam = NULL;
    }
  }
  // Call the base class PreTranslateMessage. In this example,
  // CRhinoDialog is the base class to CMyModalDialog.
  return CRhinoDialog::PreTranslateMessage( pMsg );
}