Search code examples
c#visual-studiodebuggingmanagedenvdte

Visual Studio attach to managed process programmatically


I'm trying to programmatically attach to an IISExpress process for debugging. When using the Visual Studio attach to process window I have to select Managed Code as the type to attach to. If auto detect is selected instead, VS tries to debug IISExpress as an x86/native application which does not work.

The following code (from this answer) using DTE attaches the debugger but does not appear to attach it as managed code.

public static void AttachVisualStudioToProcess(Process visualStudioProcess, Process applicationProcess)
{
    _DTE visualStudioInstance;

    if (TryGetVsInstance(visualStudioProcess.Id, out visualStudioInstance))
    {
        //Find the process you want the VS instance to attach to...
        DTEProcess processToAttachTo = visualStudioInstance.Debugger.LocalProcesses.Cast<DTEProcess>().FirstOrDefault(process => process.ProcessID == applicationProcess.Id);

        //Attach to the process.
        if (processToAttachTo != null)
        {
            processToAttachTo.Attach();

            ShowWindow((int)visualStudioProcess.MainWindowHandle, 3);
            SetForegroundWindow(visualStudioProcess.MainWindowHandle);
        }
        else
        {
            throw new InvalidOperationException("Visual Studio process cannot find specified application '" + applicationProcess.Id + "'");
        }
    }
}

Perhaps the DTE library is incapable of suggesting that the debugger should attach to managed code?


Solution

  • You need to use the Process2.Attach2() method instead, available since VS2005. It takes a debugger engine argument that specifies the kind of debugger you want to use.

    Sample code is here.