B4J Question SendKeys and Set Focus to another application

micro

Well-Known Member
Licensed User
Longtime User
Hi to all
I have a launched application on the taskbar (IconTray)
When I click with the mouse on the icon of my program the focus goes to my application, well, now how can I switch the focus to another application and simulate pressing keys on a keyboard (like SendKeys)?
How can I get this feature?
Thanks for the info that you give me
 

Erel

B4X founder
Staff member
Licensed User
Longtime User
You can use the robot API to move the mouse and click somewhere on the screen: http://docs.oracle.com/javase/7/docs/api/java/awt/Robot.html
B4X:
Sub Process_Globals
   Private robot As JavaObject
End Sub

Sub AppStart (Form1 As Form, Args() As String)
   Form1.Show
   Dim jo As JavaObject
   jo.InitializeStatic("com.sun.glass.ui.Application")
   robot = jo.RunMethodJO("GetApplication",Null).RunMethodJO("createRobot",Null)
   MouseMove(2, 2)
End Sub

   
Sub MouseMove(x As Int, y As Int)
   robot.RunMethod("mouseMove", Array As Object(x, y))
   robot.RunMethod("mousePress", Array As Object(1)) 'left button
   'Sleep(50)
   robot.RunMethod("mouseRelease", Array As Object(1)) 'left button
End Sub

Sub Sleep(ms As Long)
   Dim jo As JavaObject
   jo.InitializeStatic("java.lang.Thread").RunMethod("sleep", Array As Object(ms))
End Sub

You can also send key strokes with this API.
 
Upvote 0

micro

Well-Known Member
Licensed User
Longtime User
Ok thanks, interesting
I can use the mouse click to switch the focus to another application and then send keystrokes
while if I want to move the focus to another application from code? (No mouse click)
 
Upvote 0

micro

Well-Known Member
Licensed User
Longtime User
I think that it is not possible without calling platform specific APIs with a JNI library.
ok
Work but ther's a strange problem:
This is the sub included in your example

B4X:
Sub SendKey(code As Int)
    robot.RunMethod("keyPress", Array As Object(code))
    Sleep(100)
    robot.RunMethod("keyRelease", Array As Object(code))
End Sub

If sending SendKey(103) where 103 = "g" is printed "7"
Ok for number.
 
Upvote 0

micro

Well-Known Member
Licensed User
Longtime User
Thanks Erel
another strange problem:
If run program in debug mode o release mode by B4J all work perfectly, while if i run standalone file (jar) the program not work, crash in this line:
B4X:
robot = jo.RunMethodJO("GetApplication",Null).RunMethodJO("createRobot",Null)
Why?
 
Upvote 0

Erel

B4X founder
Staff member
Licensed User
Longtime User
You can see the error message in this case if you run it from the command line:
SS-2014-04-10_09.56.13.png


This issue will be fixed in v2.00 (first beta will be released today).
 
Upvote 0

Gabino A. de la Gala

Active Member
Licensed User
Longtime User
Upvote 0
Top