MFC: Not saving data on reboot / WM_ENDSESSION

131 views Asked by At

If I test an MFC app by sending it an WM_ENDSESSION and TRUE that is ending, the framework of MFC calls OnCloseDocument(). All good! But I find that when Windows update or the MSI Installer wants to reboot after installing something it, the 'OnCloseDocument()' is not called and all data is lost.

Looking at the MFC code you see:

// when Windows session ends, close all documents
void CFrameWnd::OnEndSession(BOOL bEnding)
{
    if (!bEnding)
        return;

    CWinApp* pApp = AfxGetApp();
    if (pApp != NULL && pApp->m_pMainWnd == this)
    {
        if (AfxGetThreadState()->m_lastSentMsg.lParam & ENDSESSION_CLOSEAPP)
        {
            // Restart Manager is restarting the application
            CDataRecoveryHandler *pHandler = pApp->GetDataRecoveryHandler();
            if (pHandler)
            {
                pHandler->SetShutdownByRestartManager(TRUE);

                // Just return here rather than doing more processing.
                // The final autosave will be handled in the WM_CLOSE handler,
                // because the Restart Manager allows 30 seconds for processing
                // that message, and only 5 seconds for processing WM_ENDSESSION.
                return;
            }
        }

        AfxOleSetUserCtrl(TRUE);    // keeps from randomly shutting down
        pApp->CloseAllDocuments(TRUE);

        // allow application to save settings, etc.
        pApp->ExitInstance();
    }
}

I presume what must be happening is the ENDSESSION_CLOSEAPP section is being called, which doesn't end up saving anything.

This is the code in the app constructor for the restart manager:

  // support Restart Manager
  m_dwRestartManagerSupportFlags=AFX_RESTART_MANAGER_SUPPORT_RESTART | AFX_RESTART_MANAGER_SUPPORT_RECOVERY;

Since I don't need autosave, but even if autosave is 5 minutes it still may not have changes saved. What is the correct way to handle it in MFC to ensure the OnCloseDocument() is called when WM_ENDSESSION is sent?

0

There are 0 answers