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)
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With