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.

Prerequisites

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

  1. Create a C# or Visual Basic Editor Classifier project. Name the solution DTETest.

  2. Add the following assembly references to the project. You have to browse to \Visual Studio installation folder\Common7\IDE\PublicAssemblies\.

    • EnvDTE.dll

    • EnvDTE80.dll

    • Microsoft.VisualStudio.Shell.Immutable.10.0

  3. 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;
    
  4. In the DTETestProvider class, import a SVsServiceProvider.

    <Import()>
    Private ServiceProvider As SVsServiceProvider = Nothing
    
    [Import]
    internal SVsServiceProvider ServiceProvider = null;
    
  5. 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));
    
  6. If you have to use the DTE2 interface, you can cast the DTE object to it.

See Also

Concepts

Editor Extension Points