3

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.

Oded
  • 489,969
  • 99
  • 883
  • 1,009
ptr0x01
  • 627
  • 2
  • 10
  • 25

2 Answers2

5

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..
}
Hans Passant
  • 922,412
  • 146
  • 1,693
  • 2,536
  • As I said it is for a menu like sytem. What if for some reason you press enter 2 times, then you would select something you didn't want to. I'll check what you wrote – ptr0x01 Feb 28 '11 at 21:06
0

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.

AbiusX
  • 2,379
  • 20
  • 26
  • or you could add a flag to dump inputs until a certain amount of time (action complete) – AbiusX Feb 28 '11 at 20:44
  • I'm not sure how you would want me to not get them out of the buffer. Is there a way to dump anything ReadKey picked up before reading the new key? Yes flag could work if it works like that, can you point me somewhere where I can read up on it? – ptr0x01 Feb 28 '11 at 20:56