views:

385

answers:

5

I am working on an application that installs a system wide keyboard hook. I do not want to install this hook when I am running a debug build from inside the visual studio (or else it would hang the studio and eventually the system), and I can avoid this by checking if the DEBUG symbol is defined.

However, when I debug the release version of the application, is there a way to detect that it has been started from inside visual studio to avoid the same problem? It is very annoying to have to restart the studio/the computer, just because I had been working on the release build, and want to fix some bugs using the debugger having forgotten to switch back to the debug build.

Currently I use something like this to check for this scenario:

System.Diagnostics.Process currentProcess = System.Diagnostics.Process.GetCurrentProcess();
string moduleName = currentProcess.MainModule.ModuleName;
bool launchedFromStudio = moduleName.Contains(".vshost");

I would call this the "brute force way", which works in my setting, but I would like to know whether there's another (better) way of detecting this scenario.

+8  A: 

Try:

System.Diagnostics.Debugger.IsAttached.

TraumaPony
A: 

I would strongly discourage the use of code that only gets run at debug time. Why? You'd like to make sure that what goes into production is what you're testing / seeing locally. This is especially true the lower level language you use as often times differences in code causes the compiler to produce your machine / IL differently.

Perhaps for the purposes of discovering an issue, but that's about it.

Russell Myers
In this case it's the other way around, actually. The hooks interfere with me being able to debug (hitting a key causes the studio and eventually every other application in which I try to enter something to freeze, because the events cannot be handled), so I do not install them in debug builds.
Grimtron
+1  A: 

@Russell Myers

I disagree. When you know you're in debug time, you can do far more checks without worrying about performance, do asserts, and all sorts of magical things.

TraumaPony
+4  A: 

For those working with Windows API, there's a function which allows you to see if any debugger is present using:

if( IsDebuggerPresent() )
{
    ...
}

Reference: http://msdn.microsoft.com/en-us/library/ms680345.aspx

Bill Casarin
A: 

Checking if you're under debugger, allow you to do some special things, like logs etc...

MANOEL F C SILVA