Disabling input in C# Console until certain task is completed

时间秒杀一切 提交于 2019-12-17 10:02:32

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!