Walkthrough: Accessing the DTE Object from an Editor Extension
By accessing the DTE object, you can automate Visual Studio in several different ways. You can get the DTE object from a Visual Studio add-in by referring to its programmatic identifier (or progID). For more information, see Referencing Automation Assemblies and the DTE2 Object. In general in VSPackages, you can get the DTE object by calling the GetService method with the type of the DTE object. For more information, see Walkthrough: Extending Managed VSPackages By Using Automation. In Managed Extensibility Framework (MEF) extensions, you can import SVsServiceProvider and then call the GetService method with a type of DTE.
To complete this walkthrough, you must install the Visual Studio 2010 SDK. For information about the Visual Studio SDK and how to download it, see Visual Studio Extensibility Developer Center on the MSDN Web site.
Getting the DTE Object
To get the DTE object from the ServiceProvider
Create a C# or Visual Basic Editor Classifier project. Name the solution DTETest.
Add the following assembly references to the project. You have to browse to \Visual Studio installation folder\Common7\IDE\PublicAssemblies\.
Go to the DTETest file, and add the following using directives (Imports statements in Visual Basic).
Imports EnvDTE Imports EnvDTE80 Imports Microsoft.VisualStudio.Shell
using EnvDTE; using EnvDTE80; using Microsoft.VisualStudio.Shell;
In the DTETestProvider class, import a SVsServiceProvider.
<Import()> Private ServiceProvider As SVsServiceProvider = Nothing
[Import] internal SVsServiceProvider ServiceProvider = null;
In the GetClassifier() method, add the following code.
Dim dte As DTE dte = CType(ServiceProvider.GetService(GetType(DTE)), DTE)
DTE dte = (DTE)ServiceProvider.GetService(typeof(DTE));
If you have to use the DTE2 interface, you can cast the DTE object to it.