B4J Question Can a Keyboard event be detected

BPak

Active Member
Licensed User
Longtime User
Check for KeyPressed?
Is there a method of checking if the 'Ctrl' Key (and other keys) are Pressed when clicking on a Canvas?
 

stevel05

Expert
Licensed User
Longtime User
Try this:
B4X:
Sub Process_Globals
    Private fx As JFX
    Private MainForm As Form
    Private Canvas1 As Canvas
End Sub

Sub AppStart (Form1 As Form, Args() As String)
    MainForm = Form1
    'Layout only holds Canvas1
    MainForm.RootPane.LoadLayout("1") 'Load the layout file.
    MainForm.Show
    
    Dim CJO As JavaObject = Canvas1
    Dim O As Object = CJO.CreateEventFromUI("javafx.event.EventHandler","CanvKeyPressed",Null)
    CJO.RunMethod("setOnKeyPressed",Array(O))
    CJO.RunMethod("setFocusTraversable",Array(True))
End Sub

'Return true to allow the default exceptions handler to handle the uncaught exception.
Sub Application_Error (Error As Exception, StackTrace As String) As Boolean
    Return True
End Sub

Sub CanvKeyPressed_Event (MethodName As String, Args() As Object) As Object
    Dim KEvt As JavaObject = Args(0)
    Log(KEvt.RunMethod("getCode",Null))
End Sub

The loaded layout only holds canvas1.
 
Upvote 0

BPak

Active Member
Licensed User
Longtime User
Thanks Steve.
It works fine. Just have to make sure the Canvas has focus and it works excellent.

Is there a way of detecting KeyDown, KeyUp with your method?
 
Upvote 0

Daestrum

Expert
Licensed User
Longtime User
setOnKeyPressed is keydown
setOnKeyReleased is keyup

so you could just add another handler for the setOnKeyReleased event

(When I used similar code, it actually stops the canvas.mouseclicked event from firing so I had to add a handler for that too.)
 
Upvote 0

BPak

Active Member
Licensed User
Longtime User
setOnKeyPressed is keydown
setOnKeyReleased is keyup

so you could just add another handler for the setOnKeyReleased event

(When I used similar code, it actually stops the canvas.mouseclicked event from firing so I had to add a handler for that too.)

Yes, that could do what I am looking at...
 
Upvote 0

BPak

Active Member
Licensed User
Longtime User
If you need to detect mouse and keyboard events when your app is not in focus, the jNativeHookB4J library will do that: https://www.b4x.com/android/forum/threads/jnativehookb4j-for-intercepting-system-input-events.55826/

I found with the sample program using Steve's example that the Focus would go to a Button I had on the Window after using KeyPressed = "UP" therefor no key press was detected by the canvas. So I redirect the focus to the Canvas and it works as expected.

Will have a look at the NativeHook. thank you.
 
Upvote 0

BPak

Active Member
Licensed User
Longtime User
Thanks for the JavaObject code...
Works as required when wanting to draw a Horizontal or Vertical Line.

Code attached for anyone interested.
 

Attachments

  • KeyPress.zip
    2.9 KB · Views: 380
Upvote 0
Top