Excel.Application.SelectionChange only fires once.

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

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

I changed it this way by adding an explicit cast type:

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

And now my event handler is called several times, and only then it stops receiving the call.

+1
source share
1 answer

Due to the way event handlers are tracked using COM Interop, the garbage collector can clear RCW, which prevents you from receiving events.

Make sure that you keep a reference to the object with an event handler, for example, instead of writing:

 Application.CurrentWorkbook.SelectionChanged += .... 

records

 class ThisAddin { WorkBook _workbook; void AddinLoaded() { _workbook.SelectionChanged += .... } } 
+7
source

Source: https://habr.com/ru/post/1399430/


All Articles