我终于弄明白了。我还需要将事件处理程序挂钩到实际的 Word 文档 (Microsoft.Office.Tools.Word.Document) 对象。(Tools.Word.Document 和 Interop.Word.Document 让我头疼……)
this.Application.DocumentBeforeClose += new Interop.Word.ApplicationEvents4_DocumentBeforeCloseEventHandler(Application_DocumentBeforeClose);
Application_DocumentBeforeClose(Interop.Word.Document document, ref bool Cancel)
{
// Documents is a list of the active Tools.Word.Document objects.
if (this.Documents.ContainsKey(document.FullName))
{
// I set the tag to true to indicate I want to cancel.
this.Document[document.FullName].Tag = true;
}
}
public MyDocument()
{
// Tools.Office.Document object
doc.BeforeClose += new CancelEventHandler(WordDocument_BeforeClose);
}
private void WordDocument_BeforeClose(object sender, CancelEventArgs e)
{
Tools.Word.Document doc = sender as Tools.Word.Document;
// This is where I now check the tag I set.
bool? cancel = doc.Tag as bool?;
if (cancel == true)
{
e.Cancel = true;
}
}
因此,由于我的所有应用程序逻辑都是在 Application 类代码中完成的,因此我需要一种方法来向 MyDocument 类事件指示我想要取消关闭事件。所以这就是我使用标签对象来保存标志的原因。