Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles
(untagged)

C# Detect if Debugger is Attached

0.00/5 (No votes)
19 Oct 2013 1  
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.

License

This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here