Wednesday, September 9, 2009

Tip : Flush the KeyBoard buffer in C#

Q) How to flush the keyboard buffer in a C# console application?

Sol:

Here’s a simple to do this :

private static void FlushKeyboard()
{
while (Console.In.Peek() != -1)
Console.In.Read();
}

Now you can use it as follows :

char x = (char)Console.Read();
FlushKeyboard();
char y = (char)Console.Read();
Console.WriteLine("{0}, {1}", x, y);

Even if you enter more than a single character after the first call to Read(), the second Read() will not be affected.

...

1 comment:

Followers