How to Disable Default Pushbutton Handling for MFC Dialog

This article has been archived. It is offered "as is" and will no longer be updated.
Summary
Windows dialog boxes support the use of a default button (pushbutton) thatis automatically activated when the ENTER key is pressed while focus is noton a command button. The MFC class library will automatically call theCDialog::OnOK() virtual function for a dialog whenever the default button(pushbutton) is activated by pressing the ENTER key.

This behavior conforms to the guidelines set forth by "The WindowsInterface: An Application Design Guide." This manual is included with theWindows version 3.1 SDK documentation. It is also available from MicrosoftPress.
More information
Although default button (pushbutton) support is recommended, you might wantto disable or modify the standard implementation in certain situations. Youcan do this in an MFC application by following these steps:

  1. Load the dialog into App Studio and change the OK button identifier from IDOK to something else such as IDC_MYOK. Also, clear the check from Default Button property.
  2. Use ClassWizard to create a message handling function for this button named OnClickedMyOK. This function will be executed when a BN_CLICKED message is received from this button.
  3. In the code for OnClickedMyOK, call the base class version of the OnOK function. Here is an example:
       void CMyDialog::OnClickedMyOK()   {      CDialog::OnOK();   }						
  4. Override OnOK for your dialog, and do nothing inside the function. Here is an example:
       void CMyDialog::OnOK()   {   }						
  5. Run the program and bring up the dialog. Give focus to a control other than the OK button. Press the RETURN key. Notice that CDialog::OnOK() is never executed.
This technique effectively disables the standard default button(pushbutton) support in an MFC program. The OK button will continue tobehave as before when activated by the mouse or through a mnemonickeystroke, but the ENTER key will not trigger OnOK handling.

This same technique can be used to disable or modify default OnCancelprocessing. The escape key generates a call to CDialog::OnCanceljust as the enter key generates an OnOK function call.
kbinf 1.00 1.50 2.00 2.10 2.50 3.00 4.00
Properties

Article ID: 122489 - Last Review: 12/04/2015 10:41:45 - Revision: 4.0

Microsoft Foundation Class Library 4.2

  • kbnosurvey kbarchive KB122489
Feedback