有没有办法检测调试器是否从C#连接到另一个进程?

Luc*_*jer 65 c# debugging

我有一个程序,Process.Start()另一个程序,它在N秒后关闭它.

有时我选择将调试器附加到已启动的程序.在这些情况下,我不希望在N秒后关闭进程.

我希望主机程序检测是否附加了调试器,因此它可以选择不关闭它.

澄清:我不想检测调试器是否附加到我的进程,我想检测调试器是否附加到我生成的进程.

Bry*_*tts 166

if(System.Diagnostics.Debugger.IsAttached)
{
    // ...
}
Run Code Online (Sandbox Code Playgroud)

  • 这不是告诉我调试器是否附加到主机进程?我正在寻找一种方法来确定生成的进程是否正在调试. (2认同)

ito*_*son 21

您需要P/InvokeCheckRemoteDebuggerPresent.这需要一个目标进程句柄,您可以从Process.Handle获取该句柄.


Dre*_*kes 14

目前正在调试的进程?

var isDebuggerAttached = System.Diagnostics.Debugger.IsAttached;
Run Code Online (Sandbox Code Playgroud)

是否正在调试另一个进程?

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);
Run Code Online (Sandbox Code Playgroud)

在Visual Studio扩展中

Process process = ...;
bool isDebuggerAttached = Dte.Debugger.DebuggedProcesses.Any(
    debuggee => debuggee.ProcessID == process.Id);
Run Code Online (Sandbox Code Playgroud)


小智 5

我知道这是旧的,但我遇到了同样的问题,并意识到如果你有一个指向EnvDTE的指针,你可以检查进程是否在Dte.Debugger.DebuggedProcesses:

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

CheckRemoteDebuggerPresent调用仅检查进程是否在本机调试,我相信 - 它不适用于检测托管调试.