Java Robot Class - Add focus to a specific running

2020-06-27 00:29发布

问题:

I am just trying to figure out if/how to get the Java Robot class to change focus from the running java app, to a specific process, such as ms word or firefox.

Thanks!

回答1:

Robot can't do that automatically. You can activate another application via alt-tab as has been suggested above, but you'll need to know the z-order of the application that you want to activate. I think that to really do this best you'll want to get the window's handle (hWnd) of the top-level window that you want to activate (if this is a Windows app), and then using the Windows user32 library functions activate the desired window. For this I recommend using JNA as one of the easiest ways (when compared to JNI). You would have to first download the JNA jna.jar and platform.jar jar files, and place them on your classpath, and then you can call most OS methods with ease. For instance, I have just this sort of thing up and running for a Windows application where I can get the hWnd for a running top-level Windows application based on the window name (full or partial), and then using that hWnd, call user32's setForegroundWindow function. If you're wanting to activate a Windows application and want to pursue this further, comment to this answer, and I can show you what code I have for this. If so, you'll want to go into greater details on exactly what it is you're trying to do.

Best of luck!



回答2:

For any that comes across this in Google as I just did:

public class activate {

    public interface User32 extends W32APIOptions {

        User32 instance = (User32) Native.loadLibrary("user32", User32.class,
                DEFAULT_OPTIONS);


        boolean ShowWindow(HWND hWnd, int nCmdShow);

        boolean SetForegroundWindow(HWND hWnd);

        HWND FindWindow(String winClass, String title);

        int SW_SHOW = 1;

    }

    public static void main(String[] args) {  
        User32 user32 = User32.instance;  
        HWND hWnd = user32.FindWindow(null, "Downloads"); // Sets focus to my opened 'Downloads' folder
        user32.ShowWindow(hWnd, User32.SW_SHOW);  
        user32.SetForegroundWindow(hWnd);  
    } 
}

Credit: http://www.coderanch.com/t/562454/java/java/FindWindow-ShowWindow-SetForegroundWindow-effect-win



回答3:

You did not specified system, 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);


标签: java awtrobot