I know one method of preventing an MFC dialog from closing when the Enter or Esc keys are pressed, but I'd like to know more details of the process and all the common alternative methods for doing so.
Thanks in advance for any help.
I know one method of preventing an MFC dialog from closing when the Enter or Esc keys are pressed, but I'd like to know more details of the process and all the common alternative methods for doing so.
Thanks in advance for any help.
When the user presses Enter key in a dialog two things can happen:
CDialog::SetDefID()
). Then a WM_COMMAND with the ID of this control is sent to the dialog.With the first option, it may happen that the default control has a ID equal to IDOK. Then the results will be the same that in the second option.
By default, class CDialog
has a handler for the WM_COMMAND(IDOK)
that is to call to CDialog::OnOk()
, that is a virtual function, and by default it calls EndDialog(IDOK)
that closes the dialog.
So, if you want to avoid the dialog being closed, do one of the following.
IDOK
.WM_COMMAND(IDOK)
that does not call EndDialog()
.CDialog::OnOk()
and do not call the base implementation.About IDCANCEL, it is similar but there is not equivalent SetDefID()
and the ESC key is hardcoded. So to avoid the dialog being closed:
WM_COMMAND(IDCANCEL)
that does not call EndDialog()
.CDialog::OnCancel()
and do not call the base implementation.There is an alternative to the previous answer, which is useful if you wish to still have an OK / Close button. If you override the PreTranslateMessage function, you can catch the use of VK_ESCAPE / VK_RETURN like so:
BOOL MyCtrl::PreTranslateMessage(MSG* pMsg)
{
if( pMsg->message == WM_KEYDOWN )
{
if(pMsg->wParam == VK_RETURN || pMsg->wParam == VK_ESCAPE)
{
return TRUE; // Do not process further
}
}
return CWnd::PreTranslateMessage(pMsg);
}
I simply override the OnOk event and instead of passing the message to the parent dialog, do nothing.
So it's basically simple as doing so:
void OnOk() override { /*CDialog::OnOK();*/ }
This should prevent the dialog from closing when pressing the return/enter key.