C# 检测调试器是否已附加






4.27/5 (9投票s)
C# 检测调试器是否已附加
此方法用于检测正在运行的进程是否附加了调试器。它涉及使用从kernel32.dll通过 PInvoke 导入的CheckRemoteDebuggerPresent
。
* 在 Visual Studio 的调试器和 OllyDbg 上测试过
如何操作...
首先,在你的程序中包含以下两行代码(这将导入 CheckRemoteDebuggerPresent
)
[DllImport("kernel32.dll", SetLastError = true, ExactSpelling = true)]
static extern bool CheckRemoteDebuggerPresent(IntPtr hProcess, ref bool isDebuggerPresent);
现在,此方法非常简单易用,因为它只需要 2 个参数
IntPtr hProcess
= 目标进程的句柄ref bool isDebuggerPresent
= 指示结果的指针
此方法完成了所有“繁重”的工作,因此不需要额外的代码:
using System;
using System.Diagnostics;
using System.Runtime.InteropServices;
public class DetectDebugger
{
[DllImport("kernel32.dll", SetLastError = true, ExactSpelling = true)]
static extern bool CheckRemoteDebuggerPresent(IntPtr hProcess, ref bool isDebuggerPresent);
public static void Main()
{
bool isDebuggerPresent = false;
CheckRemoteDebuggerPresent(Process.GetCurrentProcess().Handle, ref isDebuggerPresent);
Console.WriteLine("Debugger Attached: " + isDebuggerPresent);
Console.ReadLine();
}
}
更新
为了避免对 Debugger.IsAttached
和 IsDebuggerPresent
的任何混淆 - 抱歉我没有在技巧中更早提到这一点
IsDebuggerPresent
= 适用于任何正在运行的进程,并且也能检测到原生调试器Debugger.IsAttached
= 仅适用于当前进程,并且仅检测托管调试器。OllyDbg 将不会被此方法检测到。