We have a special use case for a PowerPoint add-in we’re developing: close host application following an event in the add-in.
“Simple! use Application.Quit();” said one coworker.
“Simple!”, said a little voice in my head.
“Watch out, this is Microsoft Office you’re talking about!”, the wise and old voice of experience whispered.
Turns out the good old experienced part of myself was right (again): you cannot use Application.Quit from an add-in. Actually, you can, but it won’t work. Once you call it, something happens with the Application object and you cannot call other methods on it, however the PowerPoint window is still active.
To really close the host application, you must use the following sequence:

private void Quit()
{
   // Close all active presentations without saving
    while( Globals.ThisAddIn.Application.Presentations.Count > 0 )
    {
        var presentation = Globals.ThisAddIn.Application.Presentations[1];
        presentation.Close();
    }
  
    // Ask the PowerPoint window to close.
    // This works fine even when multiple PowerPoint windows are open.
    var targetWnd = Globals.ThisAddIn.Application.HWND;
    PostMessage(new IntPtr( targetWnd), WM_CLOSE, 0, 0);
}

// Add the following P/Invoke declarations to your class.
[return: MarshalAs(UnmanagedType.Bool)]
[DllImport("user32.dll", SetLastError = true)]
static extern bool PostMessage(IntPtr hWnd, uint msg, Int32 wParam, Int32 lParam);
private const uint WM_CLOSE = 0x0010;
Advertisements