How to stop closing mfc application when pressing ESC key

How to stop closing mfc application by pressing ESC (Escape key). After running my application, if I press the ESC key, the window will be closed. How can this be stopped? I am using VC ++ 6.0.

+3
source share
4 answers

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

void CMyDialog::OnCancel(void)
{
   if(GetDlgItem(IDCANCEL) ==  GetFocus())
    {  
        CDialog::OnCancel();
        return;
    }
}
+4
source

There are different ways to do this. You can:

  • Create an OnCancel handler and do whatever you want with a cancellation notification
  • You can handle the OnClose event and do whatever you want.
  • PreTranslateMessage Esc , .

.

PreTranslateMessage . this

+2

OnCancel .

OnClose, , , Alt-F4 X.

PreTranslateMessage , , ...

+1

, , CDialog, "" :

  • (WM_SYSCOMMAND SC_CLOSE)
  • Window close events (WM_COMMAND with IDOK or IDCANCEL identifier)

However, MFC effectively routes the old event class through CDialog :: OnCancel by default when they are sent to the dialog box, which means that overriding OnCancel also breaks Alt-F4 and the X button. This means that in order to distinguish between the two, you you need to handle the first events in OnSysCommand, using OnOK and OnCancel overrides 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 {}
};
0
source

Source: https://habr.com/ru/post/1710560/


All Articles