Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to prevent MFC dialog closing on Enter and Escape keys?

Tags:

c++

mfc

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.

like image 545
Laxman Sahni Avatar asked Jul 24 '13 07:07

Laxman Sahni


People also ask

How do I disable MFC?

1) Through resource: Open Visual Studio, open resource file in auto mode which contains button, select the button which is to be disabled click View->Properties. In properties dialog box check Disabled checkbox.

How do I close a dialog box in MFC?

A modal dialog box closes when the user chooses one of its buttons, typically the OK button or the Cancel button. Choosing the OK or Cancel button causes Windows to send the dialog object a BN_CLICKED control-notification message with the button's ID, either IDOK or IDCANCEL.


1 Answers

When the user presses Enter key in a dialog two things can happen:

  1. The dialog has a default control (see CDialog::SetDefID()). Then a WM_COMMAND with the ID of this control is sent to the dialog.
  2. The dialog does not have a default control. Then WM_COMMAND with ID = IDOK 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.

  1. Set the default control to other than IDOK.
  2. Set a handler to the WM_COMMAND(IDOK) that does not call EndDialog().
  3. Override 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:

  1. Set a handler to the WM_COMMAND(IDCANCEL) that does not call EndDialog().
  2. Override CDialog::OnCancel() and do not call the base implementation.
like image 177
rodrigo Avatar answered Oct 06 '22 13:10

rodrigo