2

I'm developing a Visual Studio Extension to replace text in the current active .cs file using a custom command that is invoked from the right click context menu in the Code Window.

Accessing the document works so far, but if I start more than one instance of VS2017, then changes which I expect to be done in the new instance are made in the first opened instance.

Is there a possibility to get the right instance to access only the current active Document no matter how many instances are open?

At the moment I get the instance with following code:

dte = (EnvDTE.DTE)System.Runtime.InteropServices.Marshal
    .GetActiveObject("VisualStudio.DTE.15.0");    

Does anybody have an idea how to solve this?

Marcos Dimitrio
  • 6,651
  • 5
  • 38
  • 62
Vibi
  • 21
  • 2
  • Does [this answer](https://stackoverflow.com/a/46067206/10021784) to a different question help? –  Oct 26 '18 at 14:03
  • You'll have to stop using GetActiveObject(). Meant only for out-of-process usage, it is never necessary in a vsix extension. – Hans Passant Oct 26 '18 at 22:14

2 Answers2

0

You need to use in the class of your package (that inherits from the AsyncPackage base class):

EnvDTE.DTE dte = (EnvDTE.DTE) base.GetService(typeof(Microsoft.VisualStudio.Shell.Interop.SDTE));

The code that you were using returns some DTE instance running on your system, not necessarily the one where your extension is hosted.

Carlos Quintero
  • 4,300
  • 1
  • 11
  • 18
0

As Carlos Quintero already said, you should get the DTE Object by using his example.

Lets say your extension name is YourExtension:

In my case, I added a Property in my YourExtension.cs

 public EnvDTE.DTE DTEObject { get; set; }

Then in YourExtensionPackage.cs you can get the desired DTEObject right after your package got initialized:

protected override void Initialize ()
{
  YourExtension.Initialize (this);
  base.Initialize ();
  YourExtension.Instance.DTEObject = (EnvDTE.DTE)base.GetService (typeof (Microsoft.VisualStudio.Shell.Interop.SDTE));
}

Now you can work with the DTEObject within your extension and get any Object via GetObject. In My case for example I'm getting the current instance of the VersionControlEx.

Evvi
  • 21
  • 6