roshan
roshan

Reputation:

How to stop mfc dialog application from closing by pressing ESC

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.

Upvotes: 4

Views: 2236

Answers (4)

LThode
LThode

Reputation: 1963

Assuming we're dealing with a top-level window implemented as a CDialog subclass here, that window can receive two "kinds" of close events:

  • Application close events (WM_SYSCOMMAND with an ID of SC_CLOSE)
  • Window close events (WM_COMMAND with an ID of IDOK or IDCANCEL)

MFC, however, effectively routes the former class of events through CDialog::OnCancel by default when they are sent to a dialog, which means that overriding OnCancel also breaks Alt-F4 and the X button. This means that in order to distinguish between the two, you need to handle the former events in OnSysCommand while using overrides of OnOK and OnCancel to handle the latter.

The resulting code looks something like this:

class CTopLevelDlg: public CDialog
{
  afx_win void OnSysCommand(UINT id, LPARAM lparam) override
  {
    if (id == SC_CLOSE)
      CDialog::OnCancel();
  }
  void OnOK() override {}
  void OnCancel() override {}
};

Upvotes: 0

Bob Moore
Bob Moore

Reputation: 6894

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...

Upvotes: 1

tschaible
tschaible

Reputation: 7695

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())
    {  
        CDialog::OnCancel();
        return;
    }
}

Upvotes: 4

Aamir
Aamir

Reputation: 15546

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

Upvotes: 2

Related Questions