"Listen" to press a key when the thread is asleep

Is there a way to do this without an interface on the screen? I currently have this small program, other than the UI, for reading and writing information from 3280 mainframes to a text file every 60 seconds, suppose the user wants to cancel in the middle of 60 seconds of waiting, how can I “listen” for keystrokes without any events from the user interface?

+6
source share
1 answer

You need some kind of interface to capture keystrokes.

Here is an example that runs in a console application (create empty and paste defauklt into the module)

It allows you to handle "SOMETHING" in the background thread, leaving the GUI inactive for user input to commands. In this case, just a simple 1 second delay counter 1000.

Option Compare Text

Module Module1 Sub Main() Console.WriteLine("Enter ""Start"", ""Stop"", or ""Exit"".") Do Dim Com As String = Console.ReadLine Select Case Com Case "Start" Console.WriteLine(StartWork) Case "Stop" Console.WriteLine(StopWork) Case "Exit" Console.WriteLine("Quiting on completion") Exit Do Case Else Console.WriteLine("bad command Enter ""Start"", ""Stop"", or ""Exit"".") End Select Loop End Sub Public Function StartWork() As String If ThWork Is Nothing Then ThWork = New Threading.Thread(AddressOf Thread_Work) ThWork.IsBackground = False 'prevents killing the work if the user closes the window. CancelWork = False ThWork.Start() Return "Started Work" Else Return "Work Already Processing" End If End Function Public Function StopWork() As String CancelWork = True If ThWork Is Nothing Then Return "Work not currently running" Else Return "Sent Stop Request" End If End Function Public CancelWork As Boolean = False Public ThWork As Threading.Thread = Nothing Public dummyCounter As Integer = 0 Public Sub Thread_Work() Try Do dummyCounter += 1 Console.Title = "Working ... #" & dummyCounter ' ############### ' do a SMALL PART OF YOUR WORK here to allow escape... ' ############### If dummyCounter >= 1000 Then Console.Title = "Work Done at #" & dummyCounter Exit Do ElseIf CancelWork Then Exit Do End If Threading.Thread.Sleep(1000) ' demo usage only. Loop Catch ex As Exception Console.WriteLine("Error Occured at #" & dummyCounter) End Try ThWork = Nothing If CancelWork Then Console.Title = "Work Stopped at #" & dummyCounter End If End Sub End Module 
+1
source

Source: https://habr.com/ru/post/946454/


All Articles