Console application closes immediately after opening in visual studio

This is an ancient problem and has inspired several funny cartoons:

enter image description here

Let’s fix it. What you want to do is prompt the user to press the Any key when the console app was started from a shortcut on the desktop, Windows Explorer or Visual Studio. But not when it was started from the command processor running its own console. You can do so with a little pinvoke, you can find out if the process is the sole owner of the console window, like this:

using System;

class Program {
    static void Main(string[] args) {
        Console.WriteLine("Working on it...");
        //...
        Console.WriteLine("Done");
        PressAnyKey();
    }

    private static void PressAnyKey() {
        if (GetConsoleProcessList(new int[2], 2) <= 1) {
            Console.Write("Press any key to continue");
            Console.ReadKey();
        }
    }

    [System.Runtime.InteropServices.DllImport("kernel32.dll")]
    private static extern int GetConsoleProcessList(int[] buffer, int size);
}

Leave a Comment