【发布时间】:2019-08-30 01:43:08
【问题描述】:
每当特定的 MS Word 应用程序实例退出时,我都需要运行一些逻辑。我使用Microsoft.Office.Interop.Word 来:
- 创建我的 Word 应用程序实例
- 打开一个文档
- 选择一些表单域并更改其文本。
- 使 Word 应用程序对用户可见以进行交互。
- 在用户交互之后,使用
Microsoft.Office.Interop.Word.ApplicationEvents4_Event.Quit事件处理程序捕获退出事件(当用户退出 Word 时)
我正在使用现代机器开发运行 Office 365(Word 16)的应用程序,在该应用程序上触发事件在第一次尝试时没有出现问题。
但是,在运行 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");
}
【问题讨论】:
标签: c# .net winforms ms-word office-interop