简体   繁体   中英

How to read "Enter" from the keyboard to exit program

I have written a simple program in C# in Visual Studio 2013. At the end of my program I instruct the user to:

"Please Press Enter to Exit the Program."

I would like to get the input from the keyboard on the next line and if ENTER is pressed, the program will quit.

Can anyone tell me how I can achieve this function?

I have tried the following code:

Console.WriteLine("Press ENTER to close console......");
String line = Console.ReadLine();

if(line == "enter")
{
    System.Environment.Exit(0);
}

Try following:

ConsoleKeyInfo keyInfo = Console.ReadKey();
while(keyInfo.Key != ConsoleKey.Enter)
    keyInfo = Console.ReadKey();

You can use a do-while too. More informations: Console.ReadKey()

If you write the Program this way:

  • You don't need to call System.Environment.Exit(0);
  • Also you don't need to check for input key.

Example:

class Program
{
    static void Main(string[] args)
    {
        //....
        Console.WriteLine("Press ENTER to exit...");
        Console.ReadLine();
    }
}

Another Example:

class Program
{
    static void Main(string[] args)
    {
        Console.WriteLine("Press Enter in an emplty line to exit...");
        var line= "";
        line = Console.ReadLine();
        while (!string.IsNullOrEmpty(line))
        {
            Console.WriteLine(string.Format("You entered: {0}, Enter next or press enter to exit...", line));
            line = Console.ReadLine();
        }
    }
}

Yet Another Example:

If you need, you can check if the value read by Console.ReadLine() is empty, then Environment.Exit(0);

//...
var line= Console.ReadLine();
if(string.IsNullOrEmpty(line))
    Environment.Exit(0)
else
    Console.WriteLine(line);
//...

Use Console.ReadKey(true); like this:

ConsoleKeyInfo keyInfo = Console.ReadKey(true); //true here mean we won't output the key to the console, just cleaner in my opinion.
if (keyInfo.Key == ConsoleKey.Enter)
{
    //Here is your enter key pressed!
}
Console.WriteLine("Press Enter");
if (Console.ReadKey().Key == ConsoleKey.Enter)
{
    Console.WriteLine("User pressed \"Enter\"");
}

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