0

In VS2022 with "Add VSIX project(VEX0), Project->Add New Item->Extensibility->Tool Window(ToolWindow1)", I want the button_click handler to have access to the DTE. How to do this in VS2022?

2 Answers2

0

Without knowing the specifics of your current code base, it's going to be hard to make a specific recommendation here. But if you are just looking to retrieve the DTE automation interface, you can probably just invoke the Package.GetGlobalService API from your button handler.

Additional Documentation/links that you might find helpful:

Getting a service from a tool window or control container

Service Essentials

How to acquire DTE object instances in a VS Package project

Ed Dore
  • 2,013
  • 1
  • 10
  • 8
0

Here are two ways static and instance:

        public class ToolWindow1 : ToolWindowPane{
              public static DTE2 dte20;
              public DTE2 dte2;
              //public static EnvDTE.DTE dte0;
              //public EnvDTE.DTE dte;
              public ToolWindow1Control control;
              public IVsUIShell uiShell;
              /// Initializes a new instance of the <see cref="ToolWindow1"/> class.
              /// </summary>
              public ToolWindow1() : base(null){
                  ThreadHelper.ThrowIfNotOnUIThread();
                  this.Caption = "ToolWindow1";
                  //NO! dte at this point always null
                  //dte=(EnvDTE.DTE)GetService(typeof(EnvDTE.DTE));
                  //
                  this.control = new ToolWindow1Control();
                  this.Content = control;
                  control.TW1 = this;
                  control.VisibilityChanged += Control_VisibilityChanged;
              }
              private void Control_VisibilityChanged(bool isVisible){
                  ThreadHelper.ThrowIfNotOnUIThread();
                  if (isVisible){
                      // Control is visible, perform any necessary actions
                      // Your code here...

                      if (this.dte2 == null) dte2 = (DTE2)GetService(typeof(EnvDTE.DTE));
                      if (dte20 == null) dte20 = (DTE2)GetService(typeof(EnvDTE.DTE));
                      if (uiShell==null) uiShell= (IVsUIShell)GetService(typeof(IVsUIShell));
                   }
              }
          }
      }
      // ToolWindowControl.xaml.cs
      public ToolWindow1 TW1;
             public event Action<bool> VisibilityChanged;
             public ToolWindow1Control()
              {
                  this.InitializeComponent();
                  this.IsVisibleChanged += ToolWindow1Control_IsVisibleChanged;
              }
              private void ToolWindow1Control_IsVisibleChanged(object sender, DependencyPropertyChangedEventArgs e)
              {
                  bool isVisible = this.IsVisible;
                  VisibilityChanged?.Invoke(isVisible);
              }
      //....
      // <Project>Package.cs
      [ProvideService(typeof(EnvDTE.DTE))]