Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I get the DTE for running Visual Studio instance?

How do I get all the running instances of Visual Studio so that I can do automation?

(added this question because this one was closed)

like image 606
Dave Hillier Avatar asked Jan 07 '13 23:01

Dave Hillier


1 Answers

Use the running object table to get all instances, then select the one you want.

I don't think you can do better than this. It is similar to the way you attach a debugger to a VS instance. You have to select one from a list.

IEnumerable<DTE> GetInstances()
{
    IRunningObjectTable rot;
    IEnumMoniker enumMoniker;
    int retVal = GetRunningObjectTable(0, out rot);

    if (retVal == 0)
    {
        rot.EnumRunning(out enumMoniker);

        uint fetched = uint.MinValue;
        IMoniker[] moniker = new IMoniker[1];
        while (enumMoniker.Next(1, moniker, out fetched) == 0)
        {
            IBindCtx bindCtx;
            CreateBindCtx(0, out bindCtx);
            string displayName;
            moniker[0].GetDisplayName(bindCtx, null, out displayName);
            Console.WriteLine("Display Name: {0}", displayName);
            bool isVisualStudio = displayName.StartsWith("!VisualStudio");
            if (isVisualStudio)
            {
               object obj;
               rot.GetObject(moniker[0], out obj);
               var dte = obj as DTE;
               yield return dte;
            }
        }
    }
}

[DllImport("ole32.dll")]
private static extern void CreateBindCtx(int reserved, out IBindCtx ppbc);

[DllImport("ole32.dll")]
private static extern int GetRunningObjectTable(int reserved, out IRunningObjectTable prot);

For this to work in Visual Studio 2022, you will need the envdte nuget package: https://www.nuget.org/packages/envdte/17.2.32505.113

like image 104
Dave Hillier Avatar answered Nov 16 '22 06:11

Dave Hillier