Here’s a useful bit of information.  If you need to know if you are running your program in debug mode or not you can do this :

#if DEBUG
  // Program is running in debug mode
#endif

Here’s an example of why this is useful.  Say you are creating a Windows Service and we all know how boring and time consuming it can be to install the service, test it, make modifications or fixes and then test it all again, not to mention you can’t debug it properly. If you put this in the main class file

bool debugging = false;
#if DEBUG
  debugging = true;
#endif

Then we can do this :

if (!debugging)
{
  // Normal Service behaviour
  ServiceBase ServiceToRun;
  ServiceToRun = new MyService();
  ServiceBase.Run(ServiceToRun);
}
else
{
  // Run Service like a normal application
  MyService serv = new MyService();
  serv.RunStartUp();
  Debug.WriteLine("Starting in debug mode");
  System.Windows.Forms.Application.Run();
}

 

Where MyService.RunStartUp is a method which calls the OnStart method of the service class and thus “starts” the service. Now you can debug it properly :). Just remember to use the “Release” executable for everything else since the debug executable will have the DEBUG constant set to true and if you install the debug executable as a proper service it will not run correctly ( it will most likely just hang trying to start).

Tagged with:
 

One Response to Visual Studio : Detect in code if program is run in debug or release

  1. Anonymous says:

    This does not tell if you are running in the debugger, it only tells if your code was built with DEBUG settings.  It would be nice to tell if you are actively running in a debugging session or the code has been executed from the command line.

     

    BillyBob T.