The MFC Professional Stingray Software

NEWBIE TIP #5
Preventing the RETURN key from firing the OK button


You have a dialog that you want to keep on the screen until the user actually either clicks the OK button with the mouse or sets the focus to it and hits return. But when the user hits return while focus is anywhere else in the dialog box, the OK button should not fire.

You can try renaming the ID for the OK button, and use the class wizard to create a message for that new ID, but when you hit return the dialog will still disappear. The problem is that OnOK function is always called when the user hits return. You have to override it and supply an OK function of your own. So here are the steps:

  1. Change the OK dialog button ID to something other than IDOK.
  2. Turn off its default property.
  3. Create a new member function OnClickedOk using ClassWizard with the BN_CLICKED message from the new ID.
  4. Call CDialog::OnOK from this function.
  5. Add a dummy (empty) OnOK function to your dialog .cpp file and a prototype for in its header file.

See also page 125 of David Kruglinski's excellent book, Inside Visual C++ Version 4.


// This function is called when OK button is actually clicked.
void CMyDialog::OnClickedOk()
{
    if (/* all dialog data entered properly */)
    {
        CDialog::OnOK();
    }
    else
    {
        // Display appropriate error messages.
    }
}

// This function is called when user hits RETURN anywhere in dialog.
void CMyDialog::OnOK()
{
    // Do nothing.
}


Source code is provided for instructional purposes, and is released to the public domain. No claim of ownership is made. Use it at your own risk. No warranties are expressed or implied. The resulting program may not be fully functional. No animals were used to test this code.

| Past Tips | Future Tips | Home |

Comments on this Tip? Send us mail.
(Be sure to put the Tip # in the subject.)

Got an idea for a Tip you'd like us to write? Let us know.

Solved a problem lately that would make a good Tip? PLEASE tell us about it!!!
We'll give you prominent credit, and we'll even buy you a beer next time you're in town.