Thursday, 28 November 2013

How to stop console applications closing automatically?

Your console application will be closed after it finishes executing the last line in your Main() method. So if you want the application to wait until you press enter then add a Console.ReadLine() statement at the end. If you want the app to be closed for any keystroke then use Console.ReadKey()

Simple console that application waits until user presses a key

To run this code create a console application using Visual Studio and replace Program.cs file's contents with below code.

using System;

namespace SimpleConsoleApp
{
    class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine("Type-in some text and press Enter");
            string yourText = Console.ReadLine();
            Console.WriteLine("You entered: {0}", yourText);

            Console.WriteLine("Press any key to continue");

            ConsoleKeyInfo input = Console.ReadKey();

            Console.WriteLine();

            Console.WriteLine("Character pressed: {0}", 
                                                 input.KeyChar);
            Console.WriteLine("Modifiers Used: {0}", 
                                                 input.Modifiers);
            Console.WriteLine("Key Used: {0}", input.Key);

            Console.WriteLine("Press any key to exit");
            Console.ReadKey();
        }
    }
}

No comments:

Post a Comment