1

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.

Kyle Williamson
  • 2,251
  • 6
  • 43
  • 75
  • Why not use Console.ReadLine and then check the input against a valid key? – Scott Marcus Mar 18 '16 at 18:53
  • The problem with `Console.ReadLine` is that it requires the Enter/Return key to be pressed. It also allows the user to type more than one character. In certain situations, such as my example code this won't work well. My example program determines a user's reaction time to seeing "Press any key now!". Typing "C" then pressing Enter, is not the same as simply pressing the "C" key. – Kyle Williamson Mar 18 '16 at 18:56

2 Answers2

1

Clears the console buffer and corresponding console window of display information.

Put

 Console.Clear()

before

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

If that doesn't help you need to make a note that that user cannot prepress and don't ever get to Console.WriteLine("Press any key now!") if there is any button pressed or there was a button press in last 2-3 sec to avoid fast tapping.

Claudius
  • 1,883
  • 2
  • 21
  • 34
1

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
Moumit
  • 8,314
  • 9
  • 55
  • 59