How to handle Word DocumentChange event since NewDocument event does not fire on load

No NewDocument or DocumentOpen event is fired when Microsoft Word loads. When a Word instance is already open and a new or existing document opens, these events fire normally.

The assumption I saw is to handle the DocumentChange event (which always fires when Word loads) instead of the other two events.

My question is how can I do this? There are no parameters in the DocumentChange event, so how would I know when only a document (new or existing) was opened?

In addition, I already have the logic in the DocumentChange event, and the processing for new and existing documents is different, so I can’t just throw all my code into the event.

private void ThisAddIn_Startup(object sender, System.EventArgs a)
{
  this.Application.DocumentChange += new ApplicationEvents4_DocumentChangeEventHandler(Application_DocumentChange);
}

private void Application_DocumentChange()
{
  // How do I handle NewDocument or DocumentOpen?
}
+5
source share
3 answers

So, I finished processing the uploaded document in ThisAddIn_Startup. If the Document Path is an empty string, we know that the document is new and has never been saved on the local computer. In addition, I know that it is saved (including in the temp directory), and I treat it as an existing document.

private void ThisAddIn_Startup(object sender, System.EventArgs a)
{
  try
  {
    Word.Document doc = this.Application.ActiveDocument;
    if (String.IsNullOrWhiteSpace(doc.Path))
    {
      ProcessNewDocument(doc);
    }
    else
    {
      ProcessDocumentOpen(doc);
    }
  }
  catch (COMException e)
  {
    log.Debug("No document loaded with word.");
  }

  // These can be set anywhere in the method, because they are not fired for documents loaded when Word is initialized.
  ((MSWord.ApplicationEvents4_Event)this.Application).NewDocument +=
    new MSWord.ApplicationEvents4_NewDocumentEventHandler(Application_NewDocument);
  this.Application.DocumentOpen +=
    new MSWord.ApplicationEvents4_DocumentOpenEventHandler(Application_DocumentOpen);
}

Deni : DocumentOpen ThisAddIn.Desiger.cs Initialize() , NewDocument , Word, . DocumentOpen NewDocument ThisAddIn_Startup, DocumentOpen , Word.

+2

, , , ThisAddIn_Startup , DocumentOpen , .

+2

Application.Documents Startup, , . , , , ( Word) , , .

DocumentChange() , ActiveDocument. Word . Word . , . , Application.ActiveDocument .

+1

All Articles