gorkem
gorkem

Reputation: 123

confirm quit when user presses X button

i'd like to ask the user "Are you sure that you want to quit the application?" question. If the user presses Yes, the application will terminate. If the user the presses No, the application will continue running. How do i do that?

I use visual c++ 2008 and mfc.

Upvotes: 1

Views: 1721

Answers (2)

Matheno
Matheno

Reputation: 4152

You need to handle the WM_CLOSE message, which can do in MFC by adding ON_WM_CLOSE to your CMainFrame class's message map, and providing an implementation of the OnClose function.

(The Class Wizard can do this for you.)

void CMainFrame::OnClose()
{
    if (AfxMessageBox("Exit application?", MB_YESNO) == IDYES)
        __super::OnClose();
}

__super is an MSVC extension that allows you to refer to the most immediate base class. If you are compiling in another compiler (unlikely for an MFC app), or using non-standard extensions makes you uncomfortable, you can substitute the actual name of the base class.

Upvotes: 2

ScottMcP-MVP
ScottMcP-MVP

Reputation: 10425

The approach suggested by Marijke is correct. But for it to compile you must add ON_WM_CLOSE in the CMainFrame message map, and you must use the actual base class where Marijke used CFrameWnd. (There are several possible base classes.) For example, the message map could look like this if the base class is CMDIFrameWndEx:

BEGIN_MESSAGE_MAP(CMainFrame, CMDIFrameWndEx)
ON_WM_CREATE()
ON_WM_CLOSE()
....

Upvotes: 0

Related Questions