Excel.Application.SelectionChange fires only once

2019-08-11 01:10发布

问题:

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.

回答1:

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 += ....
    }
}