Android Question Loop or wait until a key is pressed

vecino

Well-Known Member
Licensed User
Longtime User
Hello, is it possible to stop the execution of the program at one point until a key is pressed?
Without using a dialog box, and if used, make it invisible.
Something like:

B4X:
Do While True
  If key.pressed Then Exit
Loop

Thank you.
 

JohnC

Expert
Licensed User
Longtime User
This might work - it also allows for a timeout value so it wont wait forever.

B4X:
Sub Globals
    Dim KP As Boolean = False   'global flag to indicate key was pressed
    Dim KC As Long = 0              'keycode of key to watch for, or if 0 then any key will trigger method
End Sub

Sub Activity_KeyPress (KeyCode As Int) As Boolean
    If KeyCode = KC or KC = 0 Then     'wait for specific keycode or anykey (if KC = 0)
        KP = True   'set flag that key was pressed
        Return True   'we are handling the keypress so OS should not do anything for this key press
    End If
End Sub

Sub WaitforKey(KCode as long, WaitSec As Long)
    Dim TT As Long    'timeout time
 
    KC = KCode  'set what key we are waiting for (0 = any key)
    KP = False    'clear flag that key was pressed
    TT = DateTime.Now + (WaitSec * DateTime.TicksPerSecond)     'calc timeout time

    Do While KP = False And DateTime.Now < TT    'wait for key or timeout
        Sleep(0)   'do background events
    Loop

    Return KP        'will return true if key pressed, or false if it timedout

End Sub
 
Last edited:
Upvote 0

JohnC

Expert
Licensed User
Longtime User
I just updated the code so you can specify the keycode to wait for, or if you specify a zero '0', then the routine will trigger on any key pressed.
 
Upvote 0
Top