问题
I'm working on a little part of my program, handling the input, basically I have this little code:
bool Done = false;
while (!Done)
{
ConsoleKeyInfo key = Console.ReadKey(true);
if (key.Key == ConsoleKey.Enter)
{
//Action
}
}
The main problem with this is that the code will handle the ReadKey even between actions.
So if you have a menu where you can press keys and then it would say "you pressed: x" if you press any buttons while it shows you this message, the ReadKey already gets that new key.
So I want to block any further input until the user sees the menu again.
回答1:
Not so sure this make sense, personally I like it when keystrokes don't disappear and I can type ahead. But you can flush the keyboard buffer like this:
while (!Done)
{
while (Console.KeyAvailable) Console.ReadKey(true);
ConsoleKeyInfo key = Console.ReadKey(true);
// etc..
}
回答2:
You can not block input, Even if you do not process it, it goes to the keyboard buffer.
You can simply stop getting them out of the buffer though.
来源:https://stackoverflow.com/questions/5147327/disabling-input-in-c-sharp-console-until-certain-task-is-completed