ericsoco
ericsoco

Reputation: 26323

Set focus of any application with Java (OSX)?

How can I set the focus (e.g. cmd+tab) of an arbitrary application (Java or not) from a Java program, on OSX?

Looking for an answer to this question, I came across this question, but it doesn't really help for OSX.

EDIT: one possibiltiy seems to be to use something like Quicksilver, and a Robot to send it keypresses with modifiers. I'd prefer something more portable, though, that requires less setup to make changes after it's compiled....

Upvotes: 2

Views: 2078

Answers (3)

Chuck
Chuck

Reputation: 237110

You can use the javax.script API to run AppleScripts. So you can write a script along the lines of "tell application "WhateverApp" to activate", filling in your arbitrary application for WhateverApp, and it should do what you want.

Upvotes: 2

millimoose
millimoose

Reputation: 39990

You should be able to reactivate an already running app using the open command that comes with OS X:

Runtime.exec("open /path/to/Whichever.app");

(Or some equivalent overload of that function.) This will also open an app if it's not running yet.

Upvotes: 4

ericsoco
ericsoco

Reputation: 26323

Chuck's answer tipped me off to osascript, so I decided to give it a shot straight from the command line. Managed to get it working with Runtime.exec(), osascript, and AppleScript.

Java launches an AppleScript and passes it the application name, using osascript from the command line, via Runtime.exec():

try {
    List<String> shellCommandList = new ArrayList<String>();
    shellCommandList.add("osascript");
    shellCommandList.add("activateApplication.scpt");
    shellCommandList.add(appName);

    String[] shellCommand = (String[])shellCommandList.toArray(new String[0]);
    Process p = Runtime.getRuntime().exec(shellCommand);

    // if desired, pipe out the script's output
    BufferedReader in = new BufferedReader(new InputStreamReader(p.getInputStream()));
    String cmdOutStr = "";
    while ((cmdOutStr = in.readLine()) != null) {
        System.out.println(cmdOutStr);
    }

    // if desired, check the script's exit value
    int exitValue = p.waitFor();
    if (exitValue != 0) {
        // TODO: error dialog
        System.err.println("Invalid application name: "+ appName);
    }
} catch (Exception e) {
    e.printStackTrace();
}

And the AppleScript uses a run handler to capture the incoming argument:

on run (arguments)
    set appName to (item 1 of arguments)
    tell application appName to activate
    return 0
end run

Upvotes: 2

Related Questions