Search code examples
c#ms-wordvstooffice-interop

Word Document.SelectionChange event does not fire


Below is my code (simplified version for readability) from a VSTO-based Word addin.

The problem is that if I have two documents open, such as documentation and a template, my addin helps develop the template and works fine until the template is closed and re-opened in the same Word instance (the documentation file kept Word alive). Once that happens the SelectionChange event is not received, even though the listener is attached (confirmed with debugger).

Is there anything wrong with this code? Any other ways to attach a selection changed event?

void Application_DocumentOpen(Word.Document Doc)
{
   // this method gets called as intended
   Document vstoDoc = Globals.Factory.GetVstoObject(doc);
   vstoDoc.SelectionChange += new Microsoft.Office.Tools.Word.SelectionEventHandler(ThisDocument_SelectionChange);
}

private void Application_DocumentBeforeClose(Word.Document doc, ref bool Cancel)
{
   // this one also gets called as intended
    Document vstoDoc = Globals.Factory.GetVstoObject(doc);
    vstoDoc.SelectionChange -= new Microsoft.Office.Tools.Word.SelectionEventHandler(ThisDocument_SelectionChange);

}

void ThisDocument_SelectionChange(object sender, SelectionEventArgs e)
{  
    // this doesn't get called if the document is closed and open again within the same Word instance
    Log("Selection changed");
}    

UPDATE: This seems like VSTO bug.

Attaching to other events works fine, I can use ContentControlOnEnter/Exit:

vstoDoc.SelectionChange += ThisDocument_SelectionChange; // doesn't work
vstoDoc.ContentControlOnEnter += vstoDoc_ContentControlOnEnter; // works
vstoDoc.ContentControlOnExit += vstoDoc_ContentControlOnExit;   // works

Solution

  • Why dont you use

    Globals.ThisAddIn.Application.WindowSelectionChange +=
                    new ApplicationEvents4_WindowSelectionChangeEventHandler(Application_WindowSelectionChange);
    

    instead of converting your Microsoft.Office.Interop.Word.Document object to Microsoft.Office.Tools.Word.Document