【发布时间】:2019-04-12 16:42:42
【问题描述】:
您好,我正在构建与 Microsoft Office word 文档 (.docx) 通信的 Windows C# WPF 应用程序。应用程序应使用用户输入更新 .docx 模板文件,并且此步骤使用 OpenXML 成功完成。该应用程序的另一部分是在应用程序窗口内或使用 MS Word 向用户显示编辑后的 Word 文档,并允许他添加更多信息。
我面临的问题是:
我应该在打开 word 文档时禁用我的应用程序控件,并在关闭 word 后启用它们,我还想知道 word 应用程序是否已保存(如果用户进行了更改)。
下一个代码是按钮单击打开word文档的事件:
using System.Windows;
using Microsoft.Office.Interop.Word;
using Application = Microsoft.Office.Interop.Word.Application;
public class MainWindowViewModel : BaseViewModel
{
...
... some view model initialization
...
public bool AreControlsEnabled { get; set; } = true;
private void OpenWord ()
{
AreControlsEnabled = false;
var app = new Application()
{
Visible = true
};
var doc = app.Documents.Open("pathtofile.docx");
var docClass = app.ActiveDocument as DocumentClass;
docClass.DocumentEvents2_Event_Close += DocClass_DocumentEvents2_Event_Close;
docClass.DocumentEvents_Event_Close += DocClass_DocumentEvents_Event_Close;
app.DocumentBeforeClose += new ApplicationEvents4_DocumentBeforeCloseEventHandler(DocBeforeClose);
app.DocumentBeforeSave += new ApplicationEvents4_DocumentBeforeSaveEventHandler(DocBeforeSave);
}
private void DocClass_DocumentEvents2_Event_Close ()
{
MessageBox.Show("DocClass_DocumentEvents2_Event_Close");
AreControlsEnabled = true;
}
private void DocClass_DocumentEvents_Event_Close ()
{
MessageBox.Show("DocClass_DocumentEvents_Event_Close");
AreControlsEnabled = true;
}
private void DocBeforeClose (Document doc, ref bool cancel)
{
MessageBox.Show("DocBeforeClose");
AreControlsEnabled = true;
}
private void DocBeforeSave (Document doc, ref bool SaveAsUI, ref bool cancel)
{
MessageBox.Show("DocBeforeSave");
AreControlsEnabled = true;
}
}
当我运行代码时 - 我看到按预期打开的 MS Word 文档,但是当我关闭它或保存时 - 没有触发任何事件,我不明白为什么。另外,我可以使用 System.Diagnostics.Process 来启动 Word 并向其添加退出事件,但这样我无法知道用户是否应用了一些更改。所以,如果有人解决了这个问题,请帮助我。
感谢您的阅读和回答
【问题讨论】: