65.9K
CodeProject is changing. Read more.
Home

C# Detect if Debugger is Attached

starIconstarIconstarIconstarIcon
emptyStarIcon
starIcon

4.27/5 (9 votes)

Oct 17, 2013

CPOL
viewsIcon

52385

C# detect if debugger is attached

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.

* tested on Visual Studio's Debugger & OllyDbg

How To...

First, include the following two lines in your program (which will import CheckRemoteDebuggerPresent):

[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

This method does all the 'hard work', so no further code is required: 

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();
    }
}

Update

In order to avoid any confusion about Debugger.IsAttached and IsDebuggerPresent - sorry I didn't mention this earlier in the tip:

  • IsDebuggerPresent = works for any running process and detects native debuggers too
  • Debugger.IsAttached = works only for the current process and detects only managed debuggers. OllyDbg won't be detected by this.