Click here to Skip to main content
15,886,519 members
Articles / Programming Languages / C#

Automate the "attach to process"

Rate me:
Please Sign up or sign in to vote.
4.86/5 (18 votes)
25 Oct 2013CPOL1 min read 55.9K   871   34  
Automating the Attach to Process from within Visual Studio.
using System;
using System.Diagnostics;
using System.Linq;
using System.Runtime.InteropServices;
using EnvDTE;
using Process = EnvDTE.Process;

namespace DebugTools
{
 /// <summary>
  /// Class ProcessExtender
  /// Attach to other processes in order to debug.
  /// Code by: Niel Morgan Thomas
  /// License: CPOL
  /// </summary>
  public static class ProcessExtender
  {
    const string progId = @"VisualStudio.DTE.10.0";
    //const string progId = @"VisualStudio.DTE.9.0"; // Vs2008

    #region -- Public Methods --

    /// <summary>
    /// Attaches Visual Studio (2010) to the specified process.
    /// </summary>
    /// <param name="process">The process.</param>
    public static void Attach(this System.Diagnostics.Process process)
    {
      // Reference visual studio core
      DTE dte;
      try
      {
        dte = (DTE) Marshal.GetActiveObject(progId); 
      } catch (COMException) {
        Debug.WriteLine(String.Format(@"Visual studio not found."));
        return;
      }

      // Try loop - visual studio may not respond the first time.
      int tryCount = 5;
      while (tryCount-- > 0)
      {
        try
        {
          Processes processes = dte.Debugger.LocalProcesses;
          foreach (Process proc in processes.Cast<Process>().Where(
            proc => proc.Name.IndexOf(process.ProcessName) != -1))
          {
            proc.Attach();
            Debug.WriteLine(String.Format("Attatched to process {0} successfully.", process.ProcessName));
            break;
          }
          break;
        }
        catch (COMException)
        {
          System.Threading.Thread.Sleep(1000);
        }
      }
    }
 
    #endregion
 
  }
}

By viewing downloads associated with this article you agree to the Terms of Service and the article's licence.

If a file you wish to view isn't highlighted, and is a text file (not binary), please let us know and we'll add colourisation support for it.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Architect
Denmark Denmark
Name: Niel Morgan Thomas
Born: 1970 in Denmark
Education:
Dataengineer from Odense Technical University.
More than 20 years in IT-business.
Current employment:
Cloud architect at University College Lillebaelt

Comments and Discussions