在Console App中阅读按键

我正在写一个小应用程序,它将等待按键,然后根据按下的键执行操作。 例如,如果没有按下任何键,它将继续等待,如果按下按键1,它将执行动作1,或者如果按下按键2,它将执行动作2.我找到了几个有用的post到目前为止, 这一个是一个例子。 从此,到目前为止,我有以下代码。

do { while (!Console.KeyAvailable) { if (Console.ReadKey(true).Key == ConsoleKey.NumPad1) { Console.WriteLine(ConsoleKey.NumPad1.ToString()); } if (Console.ReadKey(true).Key == ConsoleKey.NumPad2) { Console.WriteLine(ConsoleKey.NumPad1.ToString()); } } } while (Console.ReadKey(true).Key != ConsoleKey.Escape); 

这有几个问题,你可能已经猜到了。

1)使用ReadKey检测按下哪个键会导致暂停,这意味着必须按下该键。 我真的需要找到一种方法来避免这种情况。 可能使用KeyAvailable ,但我不确定如何使用它来检测哪个键被按下 – 任何想法?

2)由于某种原因, Escape键不会逃脱应用程序。 如果我删除if语句就行了,但是如上所述运行代码不会让我使用指定的键退出应用程序 – 任何想法?

行为的原因很简单:

只要没有按下任何键,就进入嵌套循环。 在里面,你正在等待一把钥匙并阅读它 – 所以再次没有钥匙可用。 即使你按下escape,你仍然在嵌套循环中,永远不会离开它。

你应该做的是循环,直到你有一个可用的密钥,然后读取它并检查它的值:

 ConsoleKey key; do { while (!Console.KeyAvailable) { // Do something, but don't read key here } // Key is available - read it key = Console.ReadKey(true).Key; if (key == ConsoleKey.NumPad1) { Console.WriteLine(ConsoleKey.NumPad1.ToString()); } else if (key == ConsoleKey.NumPad2) { Console.WriteLine(ConsoleKey.NumPad1.ToString()); } } while (key != ConsoleKey.Escape);