Reputation: 172
What would be the best way to exit an application when a user types x
without having to hit enter. The current code I am using is this:
Console.WriteLine("\nType x to exit > ");
string test = Console.ReadLine();
while (test != "x")
{
Console.WriteLine("\nType x to exit > ");
test = Console.ReadLine();
}
This will make the user experience better.
Upvotes: 2
Views: 4165
Reputation: 7881
You could do something like this:
do
{
Console.WriteLine("\nType x to exit > ");
}
while (Console.ReadKey().KeyChar != 'x');
Upvotes: 0
Reputation:
Console.ReadKey()
let you read a single key press. Console.readLine()
is waiting for a line termination. Here's the doc for reference:
http://msdn.microsoft.com/en-us/library/471w8d85.aspx
You can read the first character and then if it's not "x", read a line input (and prepend the first char received before).
Upvotes: 1
Reputation: 150108
You can use Console.ReadKey instead.
Obtains the next character or function key pressed by the user. The pressed key is optionally displayed in the console window.
Upvotes: 3