Thursday, August 11, 2011

How to get DTE from Visual Studio process ID?

DTE is an automation framework that is used to programmatically control Visual Studio, often from another process. It internally uses COM remoting to execute commands from another process on the VS UI thread.

A while back I have written about How to start Visual Studio programmatically and get the DTE object to control the devenv.exe process. But how to get the DTE object to automate an already running Visual Studio instance? Or how to get the DTE object to automate Visual Studio started from an experimental hive (using the /rootsuffix command line option)?

Here’s the code (need to reference EnvDTE, which is a PIA, no pun intended):

using System;
using System.Runtime.InteropServices;
using System.Runtime.InteropServices.ComTypes;
using EnvDTE;
 
public class AutomateVS
{
    [DllImport("ole32.dll")]
    private static extern int CreateBindCtx(uint reserved, out IBindCtx ppbc);
 
    public static DTE GetDTE(int processId)
    {
        string progId = "!VisualStudio.DTE.10.0:" + processId.ToString();
        object runningObject = null;
 
        IBindCtx bindCtx;
        Marshal.ThrowExceptionForHR(CreateBindCtx(reserved: 0, ppbc: out bindCtx));
 
        IRunningObjectTable rot;
        bindCtx.GetRunningObjectTable(out rot);
 
        IEnumMoniker enumMonikers;
        rot.EnumRunning(out enumMonikers);
 
        IMoniker[] moniker = new IMoniker[1];
        IntPtr numberFetched = IntPtr.Zero;
        while (enumMonikers.Next(1, moniker, numberFetched) == 0)
        {
            IMoniker runningObjectMoniker = moniker[0];
 
            string name = null;

Read more: Kirill Osenkov
QR: how-to-get-dte-from-visual-studio-process-id.aspx

Posted via email from Jasper-Net