title: Visual Studio attach to managed process programmatically
body: <p>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.</p>
  
  <p>The following code (from this <a href="https://stackoverflow.com/questions/1626458/how-to-attach-a-debugger-dynamically-to-a-specific-process/7996376#7996376">answer</a>) using DTE attaches the debugger but does not appear to attach it as managed code.</p>
  
  <pre><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&lt;DTEProcess&gt;().FirstOrDefault(process =&gt; 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 + "'");
          }
      }
  }
  </code></pre>
  
  <p>Perhaps the DTE library is incapable of suggesting that the debugger should attach to managed code?</p>