Close Button on Title Bar in MFC

2019-04-02 04:12发布

问题:

In Vc++ 6.0 Dialog Based MFC application: I do not want my user close the window by pressing the button [X] in the top-right side of the window itself and also (Alt+F4). I want to display a messageBox ("Do you really want to close the application"); if the user clicks the OK button then the application has to close, else if user clicks the CANCEL button then the application must not be closed.

回答1:

You need to implement OnClose() and only call the base class's OnClose() if you want to quit.



回答2:

Handle the WM_SYSCOMMAND message and do something like this in it.

void CMyApp::OnSysCommand(UINT nID, LPARAM lParam)
{
    if(nID == SC_CLOSE)
    {
        if(MessageBox(_T("Really"), _T("What"), MB_YESNO) == IDYES);
            //Do What you want here.
        else
            //Do something else
    }
    else
    {
        CDialog::OnSysCommand(nID, lParam);
    }
}

Here is how to add WM_SYSCOMMAND Handler to your Code:

Go to ClassView. Right click your dialog class if it is a dialog based application OR your mainframe class if it is a SDI/MDI Application. Click Properties.

In Properties Window, click on the Messages button. Scroll down to WM_SYSCOMMAND and on drop-down combo double-click to add the handler.

OR

You can do it manually as well by adding an entry in the message map. And adding declaration/definition in .h/.cpp respectively.