Home > Net >  How to get event when click destroy button before document was closed
How to get event when click destroy button before document was closed

Time:12-22

I have a problem for my MFC project as follows:

When I click on the destroy button, I want to show a messagebox "asking save file" before document closed.

But I can't.

The message is always shown after the document was closed.

A lot of places that I have placed code.

  • CloseDocument Function of Document Class
  • OnDestroy Function of MainFrame Class
  • Destructor Function of View Class
  • ExitInstance Function of App Class

But without success.

Can someone show what's wrong?

CodePudding user response:

A WM_CLOSE message is sent to a window when the user wants close it. A custom message handler can decide whether it wants to initiate window destruction from here, or go back (or initiate window destruction after storing information).

In an MFC application this is reflected as the OnClose member function of CWnd or a CWnd-derived classes (such as CFrameWnd). Client code can provide a custom implementation and wire it up through the message map. When it does it should only call into the base class implementation if it wants the program to terminate.

Assuming that your CMainFrame class derives from CFrameWnd you will need to make the following changes:

MainFrm.h (add the following class member)

class CMainFrame : public CFrameWnd
{
    // ...

protected:
    void OnClose();

    // ...
};

MainFrm.cpp (message map)

BEGIN_MESSAGE_MAP(CMainFrame, CFrameWnd)
    // ...
    ON_WM_CLOSE()
END_MESSAGE_MAP()

MainFrm.cpp (implementation)

void CMainFrame::OnClose()
{
    if (::AfxMessageBox(_T("Close application?"), MB_YESNO) == IDYES)
    {
        // Have the base class initiate destruction
        CFrameWnd::OnClose();
    } else {
        // Do nothing
    }
}

An attempt to close the application's main window pops up a confirmation dialog. If the user selects "Yes", the program terminates. Otherwise the program continues to execute. In that case the document will remain unchanged.

CodePudding user response:

The simpler approach, a Oneliner as described in MSDN

'By calling this function consistently, you ensure that the framework prompts the user to save changes before closing a document. Typically you should use the default value of TRUE for the bModified parameter. To mark a document as clean (unmodified), call this function with a value of FALSE.'

BOOL CMyDocument::OnNewDocument()
{
    if (!CDocument::OnNewDocument())
        return FALSE;

    // TODO: add reinitialization code here
    // (SDI documents will reuse this document)

    SetModifiedFlag(TRUE);    // Set this somewhere, when you want to safe the document before the document goes off

    return TRUE;
}
  • Related