18

I did find this code snippet, but it doesn't return true when I'm debugging:

[DllImport("kernel32.dll", CharSet=CharSet.Auto, ExactSpelling=true)]
internal static extern bool IsDebuggerPresent();
3
  • Only show some buttons when running in the debugger. #if debug would do! In C++ I preferred IsDebuggerPresent because it simply differentiated whether a developer was looking at it or not (in release or debug).
    – noelicus
    Sep 14, 2012 at 10:02
  • 1
    That's not correct. #if DEBUG doesnt' guarantee that you're debugging, it just states that DEBUG is set.
    – Alex
    Sep 14, 2012 at 10:03
  • @Alex That's why it was a comment. As you've stated though it's not a valid answer to the question.
    – SpaceBison
    Sep 14, 2012 at 10:08

3 Answers 3

38

Yes:

System.Diagnostics.Debugger.IsAttached
2
  • Thanks - can't believe I couldn't find this when Googling!! ... hopefully this question and answer will solve that one ;-)
    – noelicus
    Sep 14, 2012 at 10:04
  • 1
    Glad to help, please mark it as correct so others can find it more easily
    – BugFinder
    Sep 14, 2012 at 10:36
7

You tagged your question as C# so I'm assuming when saying "but it doesn't return true when I'm debugging" you actually talking about managed debugging.

The IsDebuggerPresent() function checks for a native debugger being present. In your case you should use System.Diagnostics.Debugger.IsAttached to check if a (managed) debugger is present.

Also refer to this blog post for more information on the debugger APIs.

2

The member of the .NET Framework that resembles IsDebuggerPresent() the most is obviously Debugger.IsAttached, but their internal workings are entirely different, just like Debugger.Log works very differently from simple OutputDebugString.

  • Debugger.IsAttached asks the CLR for the presence of an attached managed debugger, and never even bothers to check for the presence of a native debugger.
  • IsDebuggerPresent() asks the kernel for the presence of an attached native debugger, and has no knowledge of managed debuggers whatsoever.

As of Visual Studio 2013, the managed debugger is built on top of a native debugger, so both IsDebuggerPresent() and Debugger.IsAttached should return true when debugging a managed application under VS. But if you happen to attach Visual Studio to a managed application and explicitly override the code type to native, IsDebuggerPresent() will return true while Debugger.IsAttached still returns false.

In the end, it all comes down to what you are trying to achieve.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.