Search code examples
visual-studioenvdtevsixvspackage

Why dte.MainWindow throw a NullRefEx in VSIX Package Initialize method?


I am converting a VS Addin to a VS Package.

I have this code in my VSIX Package class(that derives from Microsoft.VisualStudio.Shell.Package)

  protected override void Initialize() {
     base.Initialize();

     var dte = this.GetService<DTE>() as DTE2;
     if(dte != null) {
        var x = dte.MainWindow;

However calling dte.MainWindow in this context throws a NullReferenceException.

enter image description here

Something must not be initialized then. When am I supposed to call dte.MainWindow then?

In the VS Addin it was working when dte.MainWindow was called from public void OnStartupComplete(ref Array custom) { in the Connect Addin type.


Solution

  • To be able to call dte.MainWindow I found the option to register to event dte.Events.DTEEvents.OnStartupComplete. As explained here, I need to keep a reference to the DTEEvents object to avoid getting it discarded.

      DTEEvents m_EventsObj;
    
      protected override void Initialize() {
         base.Initialize();
    
         var dte = this.GetService<DTE>() as DTE2;
         if(dte != null) {
    
            m_EventsObj = dte.Events.DTEEvents;
            m_EventsObj.OnStartupComplete += delegate {
                var mainWindow = dte.MainWindow; // <-- it works!!
                ...
             };