Единственный вариант, который я вижу, — создать свою альтернативу Console.ReadLine()
, которая будет реагировать не только на Enter, но и на Escape:
/// <summary>
/// Console extensions.
/// </summary>
public static class ConsoleEx
{
/// <summary>
/// Reads the next line of characters from the standard input stream.
/// </summary>
/// <returns>
/// A line of characters read from the input stream, or <c>null</c> if ESC was pressed.
/// </returns>
public static string TryReadLine()
{
StringBuilder builder = new StringBuilder();
for (;;)
{
ConsoleKeyInfo info = Console.ReadKey(true);
switch (info.Key)
{
case ConsoleKey.Enter:
Console.WriteLine();
return builder.ToString();
case ConsoleKey.Escape:
return null;
default:
Console.Write(info.KeyChar);
builder.Append(info.KeyChar);
break;
}
}
}
}
Использование в вашем случае будет таким:
string choice = ConsoleEx.TryReadLine();
switch (choice)
{
case "1":
case "2":
case "3":
Console.WriteLine(choice);
break;
case null:
// Handle ESC here.
break;
default:
Console.WriteLine("Invalid input");
break;
}