Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Console application closes immediately after opening in visual studio

I am trying to open a console application in visual studio built in C#. As soon as I open it, it closes immediately.

I know windows sets this is a a safety default (atleast I think). How do I fix this?

I know I can compile it and create a shortcut and modify the target so it has the location of the command prompt in it before the applications location. Although the programmer who created this has it generating information into the output of visual studio, so it's imperative that I only open it there.

It happens with most applications and not just in visual studio, just in this case I need it to open in VS 2010. I am using Windows 7.

like image 580
user1632018 Avatar asked Nov 28 '22 09:11

user1632018


2 Answers

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);
}
like image 97
Hans Passant Avatar answered Dec 03 '22 21:12

Hans Passant


You can also run the application by pressing (Ctrl + F5) .. This will allow it to run in 'Release' mode, and by default, you will need to press 'return' to close the window.

like image 35
d.moncada Avatar answered Dec 03 '22 21:12

d.moncada