Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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);
}
like image 900
Aaron L. W- Gabriel Avatar asked Sep 18 '15 15:09

Aaron L. W- Gabriel


People also ask

How do you end a program with enter in python?

The input() function merely waits for you to enter a line of text (optional) till you press Enter. The sys. exit("some error message") is the correct way to terminate a program. This could be after the line with the input() function.


1 Answers

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()

like image 166
DogeAmazed Avatar answered Nov 14 '22 20:11

DogeAmazed