MS Word 应用程序退出事件仅在 Word 2007 上第二次后触发

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

每当特定的 MS Word 应用程序实例退出时,我都需要 运行 一些逻辑。我正在使用 Microsoft.Office.Interop.Word 来:

  1. 创建我的 Word 应用程序实例
  2. 打开文档
  3. Select 一些表单字段并更改其文本。
  4. 使 Word 应用程序对用户可见以进行交互。
  5. 用户交互后,捕获退出事件(当用户退出Word时),使用Microsoft.Office.Interop.Word.ApplicationEvents4_Event.Quit事件处理程序

我正在使用现代机器开发我的应用程序 运行ning Office 365 (Word 16),事件在第一次尝试时没有问题地触发。

但是,在旧计算机 运行ning Word 2007 上,必须部署我正在开发的程序,该事件仅在第二次创建实例后触发。我觉得很奇怪。

这是我的代码。它 运行 在 WinForms btn_click 事件中。

//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;

OnWordQuit() 方法上我会 运行 一些逻辑,但现在我只使用消息框

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

我想问题是您将事件处理程序 OnWordQuit 附加到仅存在于您内部的局部变量 wordEventsQuit 属性 btn_click 事件处理器。

一旦 btn_click 事件处理程序完成,此变量就会超出范围。那是在 Word 实际关闭之前很久,wordEvents.Quit 事件处理程序可能会进入垃圾徽章,并且没有任何可以对此做出反应的东西。

尝试在表单 class 上声明 ApplicationEvents4_Event wordEvents 字段并将事件处理程序分配给该字段。您的代码应更改为:

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

通过这种方式,您将确保只要您的表单处于打开状态,OnWordQuit 就会继续存在...