I would like to write an application who creates input for a non-Java application in Windows. With the Robot class it's easy to generate the input, but I need to set the focus to another application's text box and enter the text over there.
Don't worry I'm not trying to write something malicious, I just want to use Java to "extend" an old application written in Delphi.
CMDOW is a command line utility which allows you to perform various window actions such as activating/deactivating, listing, minimising/maximising etc.
Alternatively, you can write a VBScript to activate another application. For example:
Set WshShell = WScript.CreateObject("WScript.Shell")
WshShell.AppActivate("Firefox")
Then use Runtime.exec
from your Java app to execute the script.
This will help you activate another application.
However, it will be much more difficult if you want to focus on a textbox within the other application and write some text.
Detecting a special application and bringing that one to the front might require a native helper, but for the moment you could send ALT+TAB to activate the "next" application
This works:
public void switchFocus() {
try {
Robot r = new Robot();
r.keyPress(KeyEvent.VK_ALT);
r.keyPress(KeyEvent.VK_TAB);
r.keyRelease(KeyEvent.VK_ALT);
r.keyRelease(KeyEvent.VK_TAB);
} catch(AWTException e) {
// handle
}
}
you just need to implement a convenience method to map chars (from a String) to key event values... (or find some existing solution)
Configure a delay otherwise it won't work:
Robot r = new Robot();
r.keyPress(KeyEvent.VK_ALT);
r.keyPress(KeyEvent.VK_TAB);
r.delay(10); //set the delay
r.keyRelease(KeyEvent.VK_ALT);
r.keyRelease(KeyEvent.VK_TAB);
On Mac, there is possible to do it with AppleScript. AppleScript is integrated to system, so it will be always functional. https://developer.apple.com/library/content/documentation/AppleScript/Conceptual/AppleScriptLangGuide/reference/ASLR_cmds.html
You need only detect you are on mac and has name of the application.
Runtime runtime = Runtime.getRuntime();
String[] args = { "osascript", "-e", "tell app \"Chrome\" to activate" };
Process process = runtime.exec(args);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With