Search code examples
c#console-applicationsleepreadkey

ReadKey getting characters pressed before a thread timeout has ended


i'm attempting my first c# console-based game. I created a centered credits intro with a "press any key to continue..." printed at the end. I used Console.ReadKey() to emulate a pause as it waits for user input. The problem is that you can 'stack' inputs, there is probably a better term but essentially, while the console is in a timeout the key inputs are still read and are queued until the timeout ends. for example;

//10 second wait
//this is where I would press a key
Thread.Sleep(10000);
char x = Console.ReadKey().KeyChar;
//x will be equal to whatever key I pressed before the timeout

this is not the functionality i'm after. does anyone have a solution to this e.g; not use Thread.Sleep() or Console.ReadKey()

If you still do not understand the question, press a key while the Thread.Sleep() is still in effect and the readkey, after the time is up will print that character. does anyone know how to stop the reading of the key?

If you would like actual project code, just ask. Although I see it as irrelevant for this question.


Solution

  • If you want to clear the buffer before waiting for a key, you can call Console.ReadKey(true) in a loop for as long as there is a KeyAvailable. Passing true to the method specifies that the key should be intercepted and not be output to the console window.

    For example:

    Thread.Sleep(TimeSpan.FromSeconds(10));
    
    // Clear buffer by "throwing away" any keys that were pressed while we were sleeping
    while(Console.KeyAvailable) Console.ReadKey(true);
    
    char x = Console.ReadKey().KeyChar;