views:

75

answers:

1

I'm writing a sample console application in VS2008. Now I have a Console.WriteLine() method which displays output on the screen and then there is Console.ReadKey() which waits for the user to end the application.

If I press Enter while the Console.WriteLine() method is displaying then the application exits.

How can I clear the input buffer before the Console.ReadKey() method so that no matter how many times the user presses the Enter button while the data is being displayed, the Console.ReadKey() method should stop the application from exiting?

+3  A: 
while(Console.KeyAvailable) 
{
    Console.ReadKey(false);
}
Console.ReadKey();
gandjustas
@gandjustas: Can you please explain what you just did?
Soham Dasgupta
@gandjustas: Very nice. I did not know about this! @Soham: Read about [`Console.KeyAvailable`](http://msdn.microsoft.com/en-us/library/system.console.keyavailable.aspx) on MSDN and I think it'll become clear.
Dan Tao
Console.KeyAvailable returns true if there is a key in input buffer. Console.ReadKey(false) reads key from buffer withot displaying it. This cycle should clear input buffer.
gandjustas
@Dan Tao: Thanks for the immediate reply. This was truly a great thing to know.
Soham Dasgupta
Console.ReadKey(false) actually does display it, .ReadKey(true) will suppress the output. Either way, THIS just made my day.
hometoast