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

前端 未结 5 1128
无人及你
无人及你 2020-11-29 03:08

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 pro

5条回答
  •  孤独总比滥情好
    2020-11-29 03:57

    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
    }
    
    
    /// Checks whether a process is being debugged.
    /// 
    /// 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.
    /// 
    /// Use the IsDebuggerPresent function to detect whether the calling process 
    /// is running under the debugger.
    /// 
    [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);
    

提交回复
热议问题