Unregister combobox SelectedIndexChanged event before AddIn shutdown

111 Views Asked by At

I am developing a MS Word 2010 AddIn, in which I have a combobox which updates a class property when it is changed:

private void comboboxFloweringStart_SelectedIndexChanged(object sender, EventArgs e)
{
    Globals.ThisAddIn.currentTaxon.FloweringStart = (short)this.comboboxFloweringStart.SelectedIndex;
}

This class is serialized on shutdown (ThisAddIn_Shutdown event handler). The combobox is located on Microsoft.Office.Tools.CustomTaskPane taxonMarkupPanel based on the user control TaxonPanel myTaxonPanel which I designed.

The problem is that at some point before the shutdown event fires, the SelectedIndexChanged event on the combobox fires and resets the value to 0, and this is the value that is serialized. I know that I could use SelectionChangeCommitted instead of SelectedIndexChanged, but I do at times set the index in code, and the event should fire in these cases too.

The CustomTaskPane does not have a close event that I could use to unsubscribe the event handler and I don't know the order of events when a VSTO is closed. Is there some other event I could subscribe to, or some other way that I can unsubscribe the SelectedIndexChanged event handler when the custom task pane / user control is closed?

1

There are 1 best solutions below

0
On BEST ANSWER

You should subscribe to the DocumentBeforeClose event of the Application, and/or Close event of the Document.

private void ThisAddIn_Startup(object sender, System.EventArgs e)
{
    Word.Application app = this.Application;
    Word.Document doc = app.ActiveDocument;
    app.DocumentBeforeClose += new Word.ApplicationEvents4_DocumentBeforeCloseEventHandler(ThisAddIn_DocumentBeforeClose);
    ((Word.DocumentEvents2_Event)doc).Close += new Word.DocumentEvents2_CloseEventHandler(ActiveDocument_Close);
}

private void ThisAddIn_DocumentBeforeClose(Word.Document doc, ref bool cancel)
{
    MessageBox.Show(string.Format ("Document {0} is closing.", doc.Name));
}

private void ActiveDocument_Close()
{
    MessageBox.Show("Active document is closing.");
}