Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using Java to set the focus to a non Java application in Windows

Tags:

java

windows

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.

like image 820
Stijn Vanpoucke Avatar asked Jan 24 '11 12:01

Stijn Vanpoucke


4 Answers

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.

like image 85
dogbane Avatar answered Nov 06 '22 12:11

dogbane


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)

like image 8
Andreas Dolk Avatar answered Nov 06 '22 13:11

Andreas Dolk


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);
like image 8
sreenath V Avatar answered Nov 06 '22 13:11

sreenath V


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);
like image 2
Radek Avatar answered Nov 06 '22 11:11

Radek