B4J Question Read keyboard's state at any given moment?

MegatenFreak

Active Member
Licensed User
Hi.
Is it possible to read the key states of the keyboard at any given part of the code?
For example, I'd like to know whether any of the arrow keys are being held down at a particular point. Something like this:
B4X:
If Keyboard.IsKeyDown("RIGHT_ARROW") Then MoveToTheRight
It seems I can't rely on normal events.
Is this possible?
(explanation: I want the user to be able to move an image around, as he wishes, using arrow keys)
 

MegatenFreak

Active Member
Licensed User
I found one solution. I'm not sure if it's the best though, performance-wise.
Using the jReflection library:
B4X:
Private Sub ActivateKeyReader
    Dim r As Reflector
    r.Target = MainForm.RootPane
    r.AddEventHandler("KPressed", "javafx.scene.input.KeyEvent.KEY_PRESSED")
    r.AddEventHandler("KReleased", "javafx.scene.input.KeyEvent.KEY_RELEASED")
End Sub

Private Sub KPressed_Event (e As Event)
    Dim jo As JavaObject = e
    Dim keycode As String = jo.RunMethod("getCode", Null)
   
    If keycode = "RIGHT" Then
        'Begin moving right
        e.Consume
    Else If keycode = "LEFT" Then
        'Begin moving left
        e.Consume
    End If
End Sub

Private Sub KReleased_Event (e As Event)
    Dim jo As JavaObject = e
    Dim keycode As String = jo.RunMethod("getCode", Null)
    
    If keycode = "RIGHT" Then
        'Stop moving right
        e.Consume
    Else If keycode = "LEFT" Then
        'Stop moving left
        e.Consume
    End If
End Sub
 
Last edited:
Upvote 0
Top