Search code examples
c#ms-wordvstooffice-interopword-addins

How to have event or run method after the document was Closed?


I have an Word AddIn (VSTO) that will process the word document after it will be closed by the user. Unfortunately, the DocumentBeforeClose event is raised even in cases where the document is not really going to close.

Ex: The event is raised before a dialog box is shown to the user prompting the user to save the document. Users are asked whether they want to save with a Yes, No, and Cancel button. If the user selects Cancel, the document remains open even though a DocumentBeforeClose event was raised. For that reason is there is any way or method to make event or Method that will be raised or run after the document was closed .

I tried to do like this:

private void ThisAddIn_Startup(object sender, System.EventArgs e)
{            
    Globals.ThisAddIn.Application.DocumentBeforeClose += new Microsoft.Office.Interop.Word.ApplicationEvents4_DocumentBeforeCloseEventHandler(this.Application_DocumentBeforeClose);

    // I want some thing like this
    Globals.ThisAddIn.Application.DocumentAfterClose += new Microsoft.Office.Interop.Word.ApplicationEvents4_DocumentOpenEventHandler(this.Application_DocumentAfterClose);
}

public void Application_DocumentBeforeClose(Word.Document doc, ref bool Cancel)
{
    MessageBox.Show(doc.Path, "Path");            
}

// I want some thing like this
public void Application_DocumentAfterClose(string doc_Path)
{
    MessageBox.Show(doc_Path, "Path");
}

Solution

  • As you already said, you can't be certain with the DocumentBeforeClose event handler that the document is actually closed afterwards. However, you can gain full control on the close process by overriding the File Close command:

    • Add commands to your Ribbon XML (for idMso FileClose):

      <customUI xmlns="http://schemas.microsoft.com/office/2006/01/customui" 
                onLoad="OnLoad"> 
         <commands> 
           <command idMso="FileClose" onAction="MyClose" /> 
         </commands> 
         <ribbon startFromScratch="false"> 
           <tabs> 
              <!-- remaining custom UI goes here -->
           </tabs> 
         </ribbon> 
      </customUI>
      
    • Providing the respective callback methods in your code:

      public void MyClose(IRibbonControl control, bool cancelDefault)
      {
          var doc = Application.ActiveDocument;
          doc.Close(WdSaveOptions.wdPromptToSaveChanges);
      
          // check whether the document is still open
          var isStillOpen = Application.IsObjectValid[doc];
      }
      

    As full sample how to customize Word commands can be found on MSDN:

    Temporarily Repurpose Commands on the Office Fluent Ribbon