21

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?

p.campbell
  • 98,673
  • 67
  • 256
  • 322
Soham Dasgupta
  • 5,061
  • 24
  • 79
  • 125

1 Answers1

40

Unfortunately, there is no built-in method in Console class. But you can do this:

while(Console.KeyAvailable) 
    Console.ReadKey(false); // skips previous input chars

Console.ReadKey(); // reads a char

Use Console.ReadKey(true) if you don't want to print skipped chars.

Microsoft References

Uwe Keim
  • 39,551
  • 56
  • 175
  • 291
gandjustas
  • 1,925
  • 14
  • 12
  • You da man! At the last second I noticed that if people banged on the keyboard they could slip through one of my pauses, the above did the trick. Thanks. – infocyde May 22 '23 at 22:28