Get input key without Console.ReadKey() func. RRS feed

  • Question

  • Hi all,

    I need a solution to get pressed key inside a console window application without Console.ReadKey().
    I found "a way" to do this using Console.KeyAvailable() on a thread looping forever and THEN checking the key via abovementioned function, but it's not as reliable as It's needed.

    The reason behind this is because If I ask user for a input such as "Enter your name:", KeyAvailable activates and Console.ReadLine() does not capture the first character pressed.

    Thanks in advance, 4D1 (thEsp) !

    Sunday, May 12, 2019 8:38 AM

All replies

  • If you are only interested in strings entered by ReadLine, then check the next example. It asks for name and, while it is entered, it plays a “beep”:

    Dim lines As New ConcurrentQueue(Of String)
    Dim t As New Thread(Sub()
                            While True
                            End While
                        End Sub)
    t.IsBackground = True
    Console.Write("Enter your name: ")
    While True
        Dim name As String = Nothing
        If lines.TryDequeue(name) Then
    ' a name is entered Console.WriteLine("Your name is: {0}.", name) Exit While Else
    ' nothing entered yet Console.Beep() Thread.Sleep(100) End If End While



    But, if you need other keys, such as arrows, etc., then this code needs adjustments. Show some details.

    • Edited by Viorel_MVP Sunday, May 12, 2019 2:17 PM
    Sunday, May 12, 2019 2:14 PM
  • Thank you Viorel, I will try the code in few minutes and give feedback !

    Thanks once again.

    Edit: Yep, your code works just fine =).

    • Edited by 4D1 (thEsp) Wednesday, May 15, 2019 9:39 PM Other...
    Wednesday, May 15, 2019 9:37 PM
  • Hi,

    Is your problem solved? If so, please mark the useful replies as answers,it will be beneficial to other community.

    Best Regards,


    MSDN Community Support Please remember to click "Mark as Answer" the responses that resolved your issue, and to click "Unmark as Answer" if not. This can be beneficial to other community members reading this thread. If you have any compliments or complaints to MSDN Support, feel free to contact MSDNFSF@microsoft.com.

    Friday, May 17, 2019 7:31 AM