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);
IntPtr fetched = IntPtr.Zero;
IMoniker[] moniker = new IMoniker[1];
while (enumMoniker.Next(1, moniker, 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);
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…