1

I Creating a Visual Studio Extension and I would like to listen when user selection item change or when current project selection change.

I try to listen - OnChange in SelectionEvents:

 var dte = ServiceProvider.GlobalProvider.GetService(typeof(EnvDTE.DTE)) as DTE2;
 var dteEvents = dte.Events as Events2;
 var selectionEvents = dteEvents.SelectionEvents;
 selectionEvents.OnChange += SelectionEventsOnOnChange;

But the OnChange event doesn't fire.

Daniel Tshuva
  • 483
  • 4
  • 12

1 Answers1

0

I found the problem.
In short: DTE events are COM object and when you handle an event to this kind of objects in a local function the GC we remove there reference.
Solution: save a private member of the events object.

private DTE2 _dte2;
private Events2 _dteEvents;
private SelectionEvents _selectionEvents;

private void OnLoaded()
{
    _dte2 = ServiceProvider.GlobalProvider.GetService(typeof(EnvDTE.DTE)) as DTE2;
    _dteEvents = _dte2.Events as Events2;
    _selectionEvents = _dteEvents.SelectionEvents;
    _selectionEvents.OnChange += SelectionEventsOnOnChange;
}
Daniel Tshuva
  • 483
  • 4
  • 12
  • 1
    Since this issue has been resolved, please mark it as the answer, so it could help other community members who get the same issue. Have a nice day:) – Jack Zhai Jan 11 '18 at 07:45