简体   繁体   中英

C# close console application when prompted?

Is there a way in C# to close the Console Application when the user inputs a letter - without using the command 'Press any key to continue...' .

ie if I write the message 'Do you want to quit (y/n) ?' and the user inputs the letter y.

namespace Example
{
    class Program
    {
        static void Main(string[] args)
        {
            Console.Write("Do you really want to quit the Game? (y, n): ");
            char YN = Console.ReadLine()[0];


            if (YN == 'y' ||
                YN == 'Y')

            {

            }
            else if (YN == 'n' ||
                 YN == 'N')
            {
                Console.WriteLine("Continue Game...");
            }
        }
    }
}

Use Environment.Exit(0) inside Y condition

    class Program
    {
        static void Main(string[] args)
        {
            Console.Write("Do you really want to quit the Game? (y, n): ");
            char YN = Console.ReadLine()[0];


            if (YN == 'y' ||
                YN == 'Y')

            {
                Environment.Exit(0);
            }
            else if (YN == 'n' ||
                 YN == 'N')
            {
                Console.WriteLine("Continue Game...");
            }
        }
    }
}

你可以抓到钥匙

  char c = Console.     ReadKey().KeyChar ;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM