How do I add support for Windows Restart Manager to my application?

Applications that use Windows Installer version 4.0 for installation and servicing on Windows Vista or above automatically use the Restart Manager to reduce system restarts. The default behavior on Windows Vista or above is to shut down applications rather than shut down and restart the operating system whenever possible.

In order to add Restart Manager support to your application you must call the following Windows Vista or above API function:

HRESULT WINAPI RegisterApplicationRestart(PCWSTR pwzCommandline, DWORD dwFlags);

Also you must handle the following Windows message: WM_QUERYENDSESSION.

RegisterApplicationRestart function will register your application with Windows Installer Restart Manager. The pwzCommandline parameter will be passed to your application when it will be automatically restarted by Restart Manager.

NoteThere is no need to specify the name of your application in this command line parameter. It will be automatically added.

The dwFlags parameter can be set to 0. For additional details please see Microsoft Platform SDK documentation.

If your application is built using Microsoft's Visual C++ 2005, all you have to do is call this function when your application starts. If you are using an earlier version of Visual C++, you need to make a stub function. Please see the example bellow for details on how to create such a stub.

...

typedef HRESULT (_stdcall *RegisterApplicationRestartT)(PCWSTR pwzCommandline, DWORD dwFlags);

...

HRESULT RegisterApplicationRestartStub(PCWSTR pwzCommandline, DWORD dwFlags)
{
  HMODULE hModule = ::LoadLibrary(_T("kernel32.dll"));
  if (hModule == NULL)
    return E_FAIL;
  RegisterApplicationRestartT proc =
    reinterpret_cast<RegisterApplicationRestartT>(::GetProcAddress(hModule, "RegisterApplicationRestart"));
  if (proc == NULL)
  {
    ::FreeLibrary(hModule);
    return E_FAIL;
  }
  HRESULT ret = (proc)(pwzCommandline, dwFlags);
  ::FreeLibrary(hModule);
  return ret;
}

When WM_QUERYENDSESSION message is received you need to save your application data. If you want your application to be automatically restarted return TRUE, otherwise return FALSE.

This method applies to GUI applications. This message must be handled in the application's main window. If you return TRUE to WM_QUERYENDSESSION message, Windows will close the application by sending WM_CLOSE to the main window.

NoteIf the restart is forced, the application will be restarted regardless of the returned value.

Please see the bellow sample code in WTL as reference:


...

BEGIN_MSG_MAP(CMainDlg)
  ...
  MESSAGE_HANDLER(WM_QUERYENDSESSION, OnQueryEndSession)
  ...
END_MSG_MAP()

...

LRESULT OnQueryEndSession(UINT /*uMsg*/, WPARAM /*wParam*/,
                          LPARAM /*lParam*/, BOOL & /*bHandled*/)
{

  // Save your application's data

  return TRUE; // allow automatic close
}