MFC Restart Manager Support in Visual C++ 2010
Windows Vista introduced the restart manager. It is used to automatically restart an application after it crashes. It can also be used to restart application after a reboot by a Windows Installer or update. If you create a new MFC application using the project wizard in Visual C++ 2010, you will automatically get support for the restart manager. If you want to add support to an existing MFC application, you only need to add 1 line of code to the constructor of your CWinApp or CWinAppEx derived class. For example:
CRestartManagerDemoApp::CRestartManagerDemoApp() { /* ... */ // support Restart Manager m_dwRestartManagerSupportFlags = AFX_RESTART_MANAGER_SUPPORT_ALL_ASPECTS; /* ... */ }
Besides this 1 line of code, you need to make sure your InitInstance function is calling the base class implementation CWinApp::InitInstance or CWinAppEx::InitInstance. That’s all there is to do to have restart manager support. That 1 line gives you:
- Recovery of unsaved documents: MFC will automatically save your unsaved documents to a temporary location. By default, MFC will automatically save your documents every 5 minutes. This can be changed with a call to SetAutosaveInterval. For example: use the following to automatically save every 5 seconds:
AfxGetApp()->GetDataRecoveryHandler()->SetAutosaveInterval(5000);
- Support for restarting after a reboot due to a Windows Installer or update.
- Support for restarting after an application crash. NOTE: there is a safeguard for this case. Windows will not restart your application if it crashed within 60 seconds of starting to prevent cyclic restarts.
When your application crashes, Windows will restart it. MFC will then check whether there were any unsaved documents and will ask you if you want them to be recovered by showing you the following dialog:
NOTE: The above dialog is a task dialog. It will only be shown when you are building a Unicode build. If you are building an ANSI build, the above task dialog is replaced with a simple message box.
The Visual Studio 2010 project below demonstrates the restart manager support. The statusbar displays the number of seconds that the application is running. Please wait until it is running for at least 60 seconds (see above). Use File > New to create some documents and add some text to them. After 60 seconds you can press the red x toolbar button to crash the application and see the restart manager in action.