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

// Tales from software development

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();
        Console.WriteLine("Press any key to exit and return to Visual Studio...");
        Console.ReadKey();
    }

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

Advertisements

Written by Sea Monkey

October 20, 2016 at 7:00 pm

Posted in Development

Tagged with ,

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: