Clear Console Buffer

2019-01-23 06:47发布

问题:

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?

回答1:

while(Console.KeyAvailable) 
{
    Console.ReadKey(false);
}
Console.ReadKey();