S h o r t S t o r i e s

// Tales from software development

Archive for October 2016

Detecting when a program is executing from the Visual Studio IDE

leave a comment »

When developing small ad hoc command line utilities in the Visual Studio IDE I often add a Console.ReadKey() method call so that I can see the console output before the program terminates and returns control the IDE. This call is removed when development is complete but I’ve often thought that it would be useful to detect if the program was executing from the IDE and, if so, pause before exiting.

I finally got round to looking at how to do this yesterday. I’d assumed that simply looking at Assembly.GetEntryAssembly() would be enough to determine that the execution was initiated by the IDE but of course Visual Studio is a lot more sophisticated than this. It appears to create an application Domain and launches the program within this domain. However, as the IDE sets itself as the Domain’s DomainManager this can be used to detect whether the program is executing from the IDE:

    // If we're running from the Visual Studio IDE then pause before exiting:
    if (AppDomain.CurrentDomain.DomainManager != null && AppDomain.CurrentDomain.DomainManager.GetType().FullName == "Microsoft.VisualStudio.HostingProcess.VSHostAppDomainManager")
        Console.WriteLine("Press any key to exit and return to Visual Studio...");

This works for Visual Studio 2010 but I haven’t tested it against other versions yet.

Written by Sea Monkey

October 20, 2016 at 7:00 pm

Posted in Development

Tagged with ,