Is there a way to detect if a debugger is attached to another process from C#?

if(System.Diagnostics.Debugger.IsAttached)
{
    // ...
}

You will need to P/Invoke down to CheckRemoteDebuggerPresent. This requires a handle to the target process, which you can get from Process.Handle.


Is the current process being debugged?

var isDebuggerAttached = System.Diagnostics.Debugger.IsAttached;

Is another process being debugged?

Process process = ...;
bool isDebuggerAttached;
if (!CheckRemoteDebuggerPresent(process.Handle, out isDebuggerAttached)
{
    // handle failure (throw / return / ...)
}
else
{
    // use isDebuggerAttached
}


/// <summary>Checks whether a process is being debugged.</summary>
/// <remarks>
/// The "remote" in CheckRemoteDebuggerPresent does not imply that the debugger
/// necessarily resides on a different computer; instead, it indicates that the 
/// debugger resides in a separate and parallel process.
/// <para/>
/// Use the IsDebuggerPresent function to detect whether the calling process 
/// is running under the debugger.
/// </remarks>
[DllImport("Kernel32.dll", SetLastError=true, ExactSpelling=true)]
[return: MarshalAs(UnmanagedType.Bool)]
private static extern bool CheckRemoteDebuggerPresent(
    SafeHandle hProcess,
    [MarshalAs(UnmanagedType.Bool)] ref bool isDebuggerPresent);

Within a Visual Studio extension

Process process = ...;
bool isDebuggerAttached = Dte.Debugger.DebuggedProcesses.Any(
    debuggee => debuggee.ProcessID == process.Id);

I know this is old, but I was having the same issue and realized if you have a pointer to the EnvDTE, you can check if the process is in Dte.Debugger.DebuggedProcesses:

foreach (EnvDTE.Process p in Dte.Debugger.DebuggedProcesses) {
  if (p.ProcessID == spawnedProcess.Id) {
    // stuff
  }
}

The CheckRemoteDebuggerPresent call only checks if the process is being natively debugged, I believe - it won't work for detecting managed debugging.