一种方法是使用EnvDTE这是Visual Studio中的COM自动化接口:
http://msdn.microsoft.com/en-us/library/envdte(VS.100).aspx
你可以在自动化接口获取通过在运行捕鱼围绕在运行Visual Studio的实例对象表(腐烂)。一旦你有了一个接口的实例,你就可以自动选择一个Visual Studio实例来附加到你想要的过程。
下面是如何做到这一点的基本示例。您将需要向EnvDTE添加对项目的引用。该组件是在我的机器上的以下位置:
C:\ Program Files文件(x86)的\微软的Visual Studio 10.0 \ Common7 \ IDE \ PublicAssemblies \ EnvDTE.dll
更新
已更新,以提供通过进程ID获取Visual Studio实例自动化接口的示例。
using System;
using System.Runtime.InteropServices;
using System.Runtime.InteropServices.ComTypes;
using EnvDTE;
namespace VS2010EnvDte
{
internal class Program
{
[DllImport("ole32.dll")]
public static extern int GetRunningObjectTable(int reserved, out IRunningObjectTable prot);
[DllImport("ole32.dll")]
public static extern int CreateBindCtx(int reserved, out IBindCtx ppbc);
private static void Main()
{
//ProcessId of the VS instance - hard-coded here.
int visualStudioProcessId = 5520;
_DTE visualStudioInstance;
if (TryGetVSInstance(visualStudioProcessId, out visualStudioInstance))
{
Process processToAttachTo = null;
//Find the process you want the VS instance to attach to...
foreach (Process process in visualStudioInstance.Debugger.LocalProcesses)
{
if (process.Name == @"C:\Users\chibacity\AppData\Local\Google\Chrome\Application\chrome.exe")
{
processToAttachTo = process;
break;
}
}
//Attach to the process.
if (processToAttachTo != null)
{
processToAttachTo.Attach();
}
}
}
private static bool TryGetVSInstance(int processId, out _DTE instance)
{
IntPtr numFetched = IntPtr.Zero;
IRunningObjectTable runningObjectTable;
IEnumMoniker monikerEnumerator;
IMoniker[] monikers = new IMoniker[1];
GetRunningObjectTable(0, out runningObjectTable);
runningObjectTable.EnumRunning(out monikerEnumerator);
monikerEnumerator.Reset();
while (monikerEnumerator.Next(1, monikers, numFetched) == 0)
{
IBindCtx ctx;
CreateBindCtx(0, out ctx);
string runningObjectName;
monikers[0].GetDisplayName(ctx, null, out runningObjectName);
object runningObjectVal;
runningObjectTable.GetObject(monikers[0], out runningObjectVal);
if (runningObjectVal is _DTE && runningObjectName.StartsWith("!VisualStudio"))
{
int currentProcessId = int.Parse(runningObjectName.Split(':')[1]);
if (currentProcessId == processId)
{
instance = (_DTE)runningObjectVal;
return true;
}
}
}
instance = null;
return false;
}
}
}
你想附加VS2010实例还是你想使用它们中的一个作为调试器? – 2010-07-16 20:12:11
我也不太清楚这是否会是有益的,所以我没有张贴此作为一个完整的解决方案,但我会看在Microsoft.VisualStudio.Debugger.Interop从Visual Studio SDK http://www.microsoft.com/启动下载/ details.aspx?FAMILYID = 47305CF4-2BEA-43C0-91CD-1B853602DCC5&displaylang = EN – 2010-07-16 20:17:34
@Henk我想用VS附加到一个单独的应用程序 – 2010-07-16 20:34:06