在控制台应用程序中阅读按键 [英] Reading Key Press in Console App
问题描述
我正在编写一个小应用程序,它将等待按键,然后根据所按的按键执行操作.例如,如果没有按键,它将继续等待;如果按键1,则将执行操作1;或者如果按键2,则将执行操作2.例如,href ="https://stackoverflow.com/questions/5891538/listen-for-key-press-in-net-console-app">一个.到目前为止,我有以下代码.
I'm writing a small application which will wait for a key press, then perform an action based on what key is pressed. For example, if no key is pressed, it will just continue waiting, if key 1 is pressed, it will perform action 1, or if key 2 is pressed it will perform action 2. I have found several helpful posts so far, this one being an example. From this, I have the following code so far.
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);
这可能有两个问题,您可能已经猜到了.
There's a couple of issue with this, which you may have guessed already.
1)
使用ReadKey
检测哪个键被按下会导致暂时的暂停,这意味着必须按下该键.我真的需要找到一种方法来避免这种情况.可能使用KeyAvailable
,但是我不确定如何使用它来检测按下了哪个键-有什么想法吗?
1)
Using the ReadKey
to detect which key is pressed results in a temporary pause, meaning the key will have to be pressed. I really need to find a way to avoid this. Possibly using KeyAvailable
, but I'm not sure how you can use this to detect which key has been pressed - any ideas?
2)
由于某些原因,Escape
键不会退出应用程序.如果我删除了if
语句,就可以了,但是按上述方式运行代码并不能让我使用指定的键退出应用程序-有什么想法吗?
2)
For some reason, the Escape
key does not escape out of the application. It does if I remove the if
statements, however running the code as is above does not let me exit the application using the designated key - any ideas?
推荐答案
该行为的原因很简单:
只要没有按键按下,您就可以进入嵌套循环. 在内部,您正在等待密钥并读取它-因此,再次没有可用的密钥. 即使您按Escape键,您仍然位于嵌套循环中,永远也不会脱离它.
You get inside the nested loop as long as there is no key pressed. Inside you are waiting for a key and read it - So again no key is available. even if you press escape, you are still inside the nested loop and never get out of it.
您应该做的是循环直到找到可用的密钥,然后读取并检查其值:
What you should of done is loop until you have a key available, then read it and check its value:
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);
这篇关于在控制台应用程序中阅读按键的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!