Message pump in a console application

后端 未结 2 712
醉梦人生
醉梦人生 2021-01-12 02:22

I have a fairly simple console application written in .NET. Sometimes the application is run in batch mode without an operator, other times it is run \"out of pocket\". If i

2条回答
  •  误落风尘
    2021-01-12 02:54

    You could use the event handling mechanism of .NET. Reposting from here.

    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
    

    Hope I helped!

提交回复
热议问题