DTEEvents.OnStartupComplete event not working for

2019-05-21 05:55发布

问题:

In the Package constructor I added the event handler for OnStartupComplete event. But when I run the code, the the event handler is not called. What am I doing wrong?

回答1:

There's a bug in VS that recycles the DTEEvents object (with your event handlers) unless you keep an explicit reference to it. You need something like this:

[ProvideAutoLoad(VSConstants.UICONTEXT.NoSolution_string)]
[ProvideAutoLoad(VSConstants.UICONTEXT.SolutionExists_string)]
class MyPackage : Package
{
    DTEEvents _EventsObj;

    protected override void Initialize()
    {
        var dte = (EnvDTE.DTE)GetService(typeof(EnvDTE.DTE));
        _EventsObj = dte.Events.DTEEvents;
        _EventsObj.OnStartupComplete += OnStartupComplete;
    }

    void OnStartupComplete()
    {
    }
}


回答2:

Try moving your code from package constructor to the Initialize() method of the package. It should help, but if it doesn't, test some other UICONTEXT_??? values for your AutoLoad attribute, maybe UICONTEXT_NoSolution ?



回答3:

See my answer here: http://social.msdn.microsoft.com/Forums/en-US/vsx/thread/eb1e8fd1-32ad-498c-98e9-25ee3da71004

I believe that it is because you could be boxing and unboxing your DTE object before doing the event subscription. This is a huge nuisance, and quite surprising that the DTE object cant be passed around easily through service location for the purpose of event subscriptions; but this seems to be the culprit.

I had tried to keep a reference to the DTE object but it made no difference as I was doing that anyway. Some events will work, and some won't; but this is consistent.