vb.netuser-inputconsole.readkey

Preventing queing/preloading a character in the console before Console.ReadKey()


When Console.ReadKey(true) is called in .NET, it reads a single keypress from the user into the console. I have noticed that a character can be typed before Console.ReadKey() is actually called, allowing a user to preload a character press before the prompt. I am looking for a way to keep this from happening.

Here is some example code to better explain:

'Code runs a loop for a few seconds'
'...'

'At this point, a user can preload a key press'

Console.WriteLine("Press any key now!")

Dim startTime As DateTimeOffset = DateTimeOffset.Now()
Console.ReadKey(True) 'The console should only look for a keypress at THIS point'
Dim endTime As DateTimeOffset = DateTimeOffset.Now()

Dim miliseconds As Integer = (endTime.Subtract(startTime).TotalMilliseconds)
Dim seconds As Double = (endTime.Subtract(startTime).TotalSeconds)
Console.Clear()
Console.WriteLine("You took {0} miliseconds or {1} second(s).", miliseconds, seconds)

If the user presses a key before the Console.ReadKey(), the sample program will return:

You took 0 miliseconds or 0 second(s).

Is there a known way to prevent this behavior? This problem occurs in other types of console programs where the user is promted to enter a specific key. If the key is pressed early, sometimes the user won't even see the prompt.


Solution

  • Below code can help you .. with test case..

    Private Shared Sub Main(args As String())
    
        'System.Threading.Thread.Sleep(4000)
    
        'rejecting old key presses
        While Console.KeyAvailable
            Console.ReadKey()
        End While
    
        Console.ReadKey()
    End Sub