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

Viewed 34631

I have a program that Process.Start() another program, and it shuts it down after N seconds.

Sometimes I choose to attach a debugger to the started program. In those cases, I don't want the process shut down after N seconds.

I'd like the host program to detect if a debugger is attached or not, so it can choose to not shut it down.

Clarification: I'm not looking to detect if a debugger is attached to my process, I'm looking to detect if a debugger is attached to the process I spawned.

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

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);
Related