How to stop mfc dialog application from closing by pressing ESC

Go To


How can I stop mfc dialog application closing by pressing ESC (Escape key). After executing my application if I press ESC key then the window is closed. How can this be stopped? I am using VC++ 6.0.

2009-06-16 10:23
by NoName


You can override the OnCancel event and only move forward with the OnCancel call if IDCANCEL is the focused item.

void CMyDialog::OnCancel(void)
   if(GetDlgItem(IDCANCEL) ==  GetFocus())
2009-06-16 10:35
by tschaible


There are different ways to do this. You can:

  1. Create an OnCancel Handler and do whatever you want with the Cancel notification
  2. You can Handle OnClose Event and do whatever you want.
  3. You can override PreTranslateMessage and check Esc key there and do whatever you want.

Check this for code examples.

For a PreTranslateMessage example, see this

2009-06-16 10:35
by Aamir
OnClose (the designated handler of WM_CLOSE) is not being called by the Esc key press - Alan Baljeu 2017-10-31 15:44


Override OnCancel and don't call the base class implementation.

Don't go near OnClose unless you know what you're doing, you risk breaking the behaviour for Alt-F4 and the X button.

I've always regarded PreTranslateMessage for things like this as using a thermo-nuclear weapon to crack a nut, but if it floats your boat...

2009-06-16 21:38
by Bob Moore