سؤال

I have an event hooked up to the DocumentBeforeClose event for a Microsoft Word document in C#.

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

If some logic is true, I set the Cancel flag to true, so that the document won't close. However, although the event is fired and the Cancel flag is set to true, the document still closes.

Is this a bug?

هل كانت مفيدة؟

المحلول

I finally figured it out. I needed to also hook an event handler to the actual Word Document (Microsoft.Office.Tools.Word.Document) object as well. (Tools.Word.Document and Interop.Word.Document give me headaches...)

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

So since all of my application logic is done in the Application class code, I needed a way to indicate to my MyDocument class event that I want to cancel the close event. So that's why I use the tag object to save the flag.

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top