C# Detect if Debugger is Attached
September 9th, 2013 | Apex | Security

This method is used to detect if a running process has a debugger attached to it. It involves using CheckRemoteDebuggerPresent, imported from kernel32.dll via PInvoke.

It's a neat way to add a little bit of protection to your program, but don't expect too much since .NET is far from being safe.

* tested on Visual Studio's Debugger & OllyDbg

How to...

First, include the following lines in your program:

[DllImport("kernel32.dll", SetLastError = true, ExactSpelling = true)]
static extern bool CheckRemoteDebuggerPresent(IntPtr hProcess, ref bool isDebuggerPresent);

Now, this method is pretty simple to use since it takes only 2 arguments:

  1. IntPtr hProcess = the target process' handle
  2. ref bool isDebuggerPresent = pointer that indicates the result

Since it's pretty straightforward, I guess there's no need for additional details - in any case you can find the complete source code below:

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 ?

In order to avoid any confusion about Debugger.IsAttached and CheckRemoteDebuggerPresent - sorry I didn't mentioned this earlier in the article:

Tags: C# Detect any Debugger; C# CheckRemoteDebuggerPresent vs Debugger.IsAttached; C# Detect Debugger; C# If Debugger Attached;