Search code examples
c#.netwinformsms-wordoffice-interop

MS Word Application Quit Event only firing after second time on Word 2007


I need to run some logic whenever a specific MS Word Application instance quits. I'm using Microsoft.Office.Interop.Word to:

  1. Create my Word Application Instance
  2. Open a document
  3. Select some form fields and changing their text.
  4. Make the Word Application visible for the user to interact.
  5. After the user interaction, capture the quit event (when the user exits Word), using Microsoft.Office.Interop.Word.ApplicationEvents4_Event.Quit event handler

I'm using a modern machine to develop my app running Office 365 (Word 16), on which the event fires without a problem on the first try.

However, on an older machine running Word 2007, where the program I'm developing must be deployed, the event only fires after the second time the instance is created. Weird, I think.

Here's my code. It runs inside a WinForms btn_click event.

//instantiate word application
Microsoft.Office.Interop.Word.Application wordApp = null;
wordApp = new Microsoft.Office.Interop.Word.Application();

//open document
Document wordDoc = wordApp.Documents.Open(WordDocumentPath);
//use a dictionary to fill in the form fields
foreach (KeyValuePair<string, string> fieldValue in FieldsValues)
{
    FormField formField = wordDoc.FormFields[fieldValue.Key];
    formField.Select();
    formField.Result = fieldValue.Value;
}

//make Word UI visible and bring to front
wordApp.Visible = true;
wordDoc.Activate();
wordApp.Activate();

//handle quit event
ApplicationEvents4_Event wordEvents = wordApp;
wordEvents.Quit += OnWordQuit;

On OnWordQuit() method I will run some logic, but right now I'm only using a message box

//only runs on Word 2007 when I click the button for the second time
private void OnWordQuit()
{
    MessageBox.Show("OnWordQuit");
}

Solution

  • I guess the problem is that you’re attaching you event handler OnWordQuit to the Quit property of the local variable wordEvents that exists only within you btn_click event handler.

    This variable goes out of scope as soon as btn_click event handler is completed. That is long before the Word is being actually closed the wordEvents.Quit event handler may go to the garbadge and there is nothing that could react to that.

    Try to declare ApplicationEvents4_Event wordEvents field on your Form class and assign event handler to this field. Your code should be changed like this:

    //ApplicationEvents4_Event wordEvents = wordApp;
    this.wordEvents.Quit += OnWordQuit;     //  field or property ApplicationEvents4_Event wordEvents should be defined on the form class
    

    In such a way you will ensure that OnWordQuit would survive as long as your form is open...