Page 1 of 1

Waiting For Key Press: Console App Rate Topic: -----

#1 trevster344  Icon User is offline

  • The Peasant
  • member icon

Reputation: 225
  • View blog
  • Posts: 1,526
  • Joined: 16-March 11

Posted 09 November 2011 - 10:40 PM

Often I see the question "How do I check for a key press without stopping my code from being run?". I came up with a solution using threading, and timers. My program counts each second until a key is pressed, to which it displays the key pressed and restarts counting. It's not very complex at all, and granted there are probably many other ways to get it done than mine, I chose my method just to simply demonstrate it being done. Thank you. :)

Imports System.Threading.Thread

Module Module1
    Private Second As Integer = 1
    Private Tick As New Timers.Timer(1000)

    Sub Main()

        AddHandler tick.Elapsed, AddressOf Ticker 'Event for the timer tick

        Dim NewThread As System.Threading.Thread = New System.Threading.Thread(AddressOf LookForKeyPress) 'New thread to check for key press
        NewThread.Start() 'Start thread

        Console.WriteLine("Now awaiting key presses...")
        tick.Enabled = True 'Enable the timer
    End Sub

    Private Sub Ticker()
        'every tick this sub is called and the seconds are displayed till a key is pressed
        Console.WriteLine(Second)
        Second += 1

    End Sub

    Private Sub LookForKeyPress()

        While True
            Dim k As ConsoleKeyInfo = Console.ReadKey() 'read for a key press
            If Not k.Key.ToString.Length <= 0 Then 'check the length of the key string pressed, mainly because the key in this case will be apart of the system.consolekey
                Console.WriteLine(Environment.NewLine & "Key Pressed: " & k.Key.ToString) 'display the key pressed
                Second = 1 'restart the timer
            End If
        End While

    End Sub

End Module



Is This A Good Question/Topic? 3
  • +

Replies To: Waiting For Key Press: Console App

#2 Israel  Icon User is offline

  • D.I.C Addict
  • member icon

Reputation: 7
  • View blog
  • Posts: 821
  • Joined: 22-November 04

Posted 13 November 2011 - 02:15 PM

Nice! I'd like to see this in more languages.
Was This Post Helpful? 0
  • +
  • -

#3 AdamSpeight2008  Icon User is offline

  • MrCupOfT
  • member icon

Reputation: 2298
  • View blog
  • Posts: 9,535
  • Joined: 29-May 08

Posted 13 November 2011 - 03:24 PM

Very basic tutorial, lack depth. What if I want to do something based on the key pressed? How do I that?

Note: If your use .net4.0 or higher I strongly suggest using the task based approach rather that threads. url="http://www.dreamincode.net/code/snippet5821.htm"]See snippet.[/url]
Was This Post Helpful? 0
  • +
  • -

#4 trevster344  Icon User is offline

  • The Peasant
  • member icon

Reputation: 225
  • View blog
  • Posts: 1,526
  • Joined: 16-March 11

Posted 14 November 2011 - 07:29 PM

Thanks Adam I just wanted to throw a basic example for those who google or search cause I see it come up a lot. Appreciate the input it's my first tutorial. :)
Was This Post Helpful? 0
  • +
  • -

#5 sprintwatch  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 3
  • Joined: 28-September 10

Posted 22 November 2011 - 05:18 PM

Hi,

Great tutorials, it run smoothly. I ask a favor, how can do that like a simple game.

let say typing a words using timer like your sample program. the interval is 10 seconds and if the user
can type a certain words within the range of time they minus the given life a total of 3. at the same time has done, the total score will display.

Thanks in advance!!
Was This Post Helpful? 0
  • +
  • -

#6 trevster344  Icon User is offline

  • The Peasant
  • member icon

Reputation: 225
  • View blog
  • Posts: 1,526
  • Joined: 16-March 11

Posted 22 November 2011 - 05:50 PM

Hi there will discuss in private message later today.
Was This Post Helpful? 0
  • +
  • -

#7 trevster344  Icon User is offline

  • The Peasant
  • member icon

Reputation: 225
  • View blog
  • Posts: 1,526
  • Joined: 16-March 11

Posted 14 April 2017 - 04:46 PM

Just wanted to update with a task based approach as was recommended many years ago.

    'Total number of questions answered
    Private timesAnswered As Integer = 0

    Sub Main()
        
        LoadQuestions() 'Load questions

        While True
            'Keep the application from closing prematurely
        End While

    End Sub

    Public Async Sub LoadQuestions()
        Dim question As String = ""
        Dim answer As String = ""
        Select Case New Random().Next(1, 3)
            Case 1
                question = "What is your name?"
            Case 2
                question = "How old are you?"
            Case 3
                question = "What is your favorite color?"
        End Select

        Console.WriteLine(question) 'Display question
        answer = Await getLastAnswer() 'Await the last questions answer
        Console.WriteLine(answer & " was the answer entered.") 'Display what was considered an answer.
        timesAnswered += 1 'Increment total questions answered

        If timesAnswered < 3 Then 'Load next question
            LoadQuestions()
        Else 'Finished answering questions
            Console.WriteLine("Thank you for answering these 3 short questions. Take care.")
            Threading.Thread.Sleep(3000) 'Give user time to read message
            Environment.Exit(0) 'Shutdown console application
        End If
    End Sub

    Public Async Function getLastAnswer() As Task(Of String)

        Return Await Task.Run(Function()
                                  Dim t As String = ""
                                  While True
                                      t = Console.ReadLine 'Read next line input

                                      If t.Length > 0 And t.StartsWith("#") Then 'Grab answer
                                          Exit While 'Exit loop and return answer input
                                      ElseIf t.Length > 0 And t.ToLower = "exit" Then 'Exit application
                                          Environment.Exit(0) 'Close application
                                      ElseIf t.Length > 0 Then 'Display message telling user their input was invalid
                                          Console.WriteLine("I'm sorry I can't see you. Please start your answer with a '#'.")
                                      End If
                                  End While
                                  Return t 'Return accepted answer
                              End Function)

    End Function



Was This Post Helpful? 0
  • +
  • -

Page 1 of 1