Daniel Oakley Daniel Oakley -3 years ago 164
Vb.net Question

VB.NET 2010 Console Application Wait for a key for 5 seconds, carry on if not

Ok, so I've tried looking up on several Google sites and cannot find
an answer for this.

Its in VB.Net as a Console Application, the way I want to set this up is almost like BIOS entry, when you turn your computer on you have several seconds to press a key, if its not pressed it will skip on, this is easy enough in a Windows Forms application with a timer, but I'm struggling to do it in Console application.

code so far:

Console.WriteLine("Welcome to console, press F2 for advanced options.")
''Console.ReadKey(keys.f2)
''Make it pause for 5 seconds, tried obvious threading,thread.sleep(5000) - that halts the application :/


So yeah, if you understand what I mean and are able to help out, anything is appreciated. There doesn't seem to be any obvious timer function. I was thinking of having a variable that slowly increments to 100, and uses thread.sleep, but I think its chance of picking up the key is low because .sleep halts the application.
Was also thinking of console.readkey, but unsure how to read a specific key during the wait process.

Answer Source

Using a Do loop, Console.KeyAvailable, and a stopwatch

    Console.WriteLine("Welcome to console, press F2 for advanced options.")
    Dim stpw As Stopwatch = Stopwatch.StartNew
    Dim waitfor As New TimeSpan(0, 0, 5)
    Dim kp As ConsoleKeyInfo

    Do
        If Console.KeyAvailable Then
            kp = Console.ReadKey(True)
            If kp.Key = ConsoleKey.F2 Then
                Exit Do
            End If
        End If
    Loop While stpw.Elapsed < waitfor

    If kp.Key = ConsoleKey.F2 Then
        Console.WriteLine("F2 press")
    Else
        Console.WriteLine("NO F2")
    End If
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download