How can I have my program execute some code only if run from the Visual Studio debugger?

Raymond Chen

A customer wanted their program to operate in a special mode if it is being debugged from inside the Visual Studio development environment. Say, if being run from Visual Studio via the “Start with debugging” menu, it should display a diagnostic window that contains additional information.

You should think twice before you do this.

Sure. you could use a function like Is­Debugger­Present to sniff whether your process is being debugged, and if so turn on additional features suitable for debugging. But you also run into the risk of having a bug that occurs only when your program isn’t being debugged.¹ And everybody hates those types of bugs.

You should have a command line switch that enables the diagnostic window. You can configure Visual Studio so that when you run the program under Visual Studio, it gets the command line switch. That way, when you have a bug that goes away when the diagnostic window is open, you can remove the command line switch and debug it. (It also means that when run outside Visual Studio, you can give the special command line switch and get the diagnostics window even though no debugger is running.)

As a compromise, you could enable the diagnostic window by default if Is­Debugger­Present reports that there is a debugger, but make sure you have a command line switch to override that call and disable the diagnostic window so that you can debug the bugs that occur only when the diagnostic window is not present.

¹ Maybe the diagnostic window calls some functions that have side effects which are masking a bug in the program. For example, the diagnostic window might perform extra logging, which introduces a change in timing that masks a race condition.

0 comments

Discussion is closed.

Feedback usabilla icon