关闭事件之前的MS Word文档不会取消

时间:2012-09-25 17:12:30

标签: c# .net ms-word office-interop word-2010

我有一个事件连接到DocumentBeforeClose事件,用于C#中的Microsoft Word文档。

this.Application.DocumentBeforeClose +=
                new MSWord.ApplicationEvents4_DocumentBeforeCloseEventHandler(Application_DocumentBeforeClose);

如果某些逻辑为真,我将Cancel标志设置为true,以便文档不会关闭。但是,虽然触发了事件并且Cancel标志设置为true,但文档仍然关闭。

这是一个错误吗?

1 个答案:

答案 0 :(得分:2)

我终于明白了。我还需要将事件处理程序挂钩到实际的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类事件指示我要取消close事件。这就是我使用tag对象来保存标志的原因。

相关问题