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

前端 未结 5 1112
无人及你
无人及你 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:38

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

    0 讨论(0)
  • 2020-11-29 03:43
    if(System.Diagnostics.Debugger.IsAttached)
    {
        // ...
    }
    
    0 讨论(0)
  • 2020-11-29 03:50

    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.

    0 讨论(0)
  • 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
    }
    
    
    /// <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);
    
    0 讨论(0)
  • 2020-11-29 04:01

    The solution for me is Debugger.IsAttached as described here: http://www.fmsinc.com/free/NewTips/NET/NETtip32.asp

    0 讨论(0)
提交回复
热议问题