Daniel
Daniel

Reputation: 21

SolutionEvents for Visual studio 2010 addin does not fire

I'm building an visual studio 2010 addin and trying to hook into an event when the solution is loaded.

Basically what I have found is that SolutionEvents.Opened seems to be what I'm looking for, however listening to it in OnConnection does not seem to be working:

public void OnConnection(object application, ext_ConnectMode connectMode, object addInInst, ref Array custom)
{
  applicationObject = (DTE2)application;
  var outputWindow = (OutputWindow)applicationObject.Windows.Item(Constants.vsWindowKindOutput).Object;
  outputWindowPane = outputWindow.OutputWindowPanes.Add("My Pane");
  applicationObject.Events.SolutionEvents.Opened += SolutionEventsOnOpened;
  outputWindowPane.OutputString("Connected");
}

private void SolutionEventsOnOpened()
{
  outputWindowPane.OutputString("SolutionEventsOnOpened");
}

The only thing outputed is "Connected".

I have tried to listen to SolutionItemsEvents.ItemAdded and SolutionEvents.ProjectAdded and also they do not fire.

Should I init the events elsewhere? (Note I have R# installed, perhaps it is knowed to cause issues?)

Upvotes: 2

Views: 690

Answers (2)

Patrick from NDepend team
Patrick from NDepend team

Reputation: 13842

With VS2010, when opening a .sln file that leads to start a new VS2010 instance, it is worth noting that SolutionEvents.Opened is fired before EventsObj.OnStartupComplete is fired. So if you register SolutionEvents.Opened during EventsObj.OnStartupComplete it won't fire in this situation.

As far as I know all VS versions post-2010 [2012-2019] fire SolutionEvents.Opened after EventsObj.OnStartupComplete is fired.

Upvotes: 0

Webreaper
Webreaper

Reputation: 622

Found the solution here: http://blogs.microsoft.co.il/blogs/kolbis/archive/2007/11/22/hooking-up-to-the-solution-events.aspx

Basically, you need to declare members at your add-in class scope for the SolutionEvents and Events variables, and assign them, and then reference the eventhandlers through that. E.g.

    private Events2 m_events;
    private SolutionEvents m_solutionEvents;

then in the OnConnection handler (when your plugin gets initialised) do this:

    m_application = Application as DTE2;

    m_events = (Events2)m_application.Events;
    m_solutionEvents = m_events.SolutionEvents;

and finally, wire up the solution Opened/AfterClosing events, as follows:

    m_solutionEvents.Opened += m_openSolution;
    m_solutionEvents.AfterClosing += m_closeSolution;

Then the events will fire.

I presume the reason for doing this is because otherwise the Events/SolutionEvents objects get changed or GC'd (or both ;-).

HTH

Upvotes: 4

Related Questions