2

I'm getting only the first event notification, and nothing happens after. Any ideas?
UPD: I've found a strange thing. My code for event handler looked like this:

                    var cell = range.Cells[1, 1];
                    var rangeName = cell.Address[false, false, XlReferenceStyle.xlA1, Type.Missing, Type.Missing];

I've changed it in this way, adding explicit type cast:

                    var cell = (Range)range.Cells[1, 1];
                    var rangeName = cell.Address[false, false, XlReferenceStyle.xlA1, Type.Missing, Type.Missing];

And now my event handler gets called several times, and only then stops getting called.

user626528
  • 13,999
  • 30
  • 78
  • 146

1 Answers1

8

Because of the way event handlers are tracked with COM Interop, the garbage collector can clean up the RCW's which stops you from receiving events.

Make sure you keep a reference to the object that has the event handler, for instance instead of writing:

Application.CurrentWorkbook.SelectionChanged += ....

write

class ThisAddin
{
    WorkBook _workbook;

    void AddinLoaded()
    {
        _workbook.SelectionChanged += ....
    }
}
Jake Ginnivan
  • 2,112
  • 16
  • 20