Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java Robot Class - Add focus to a specific running Application?

Tags:

java

awtrobot

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!

like image 387
Johnrad Avatar asked Dec 12 '22 01:12

Johnrad


1 Answers

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!

like image 115
Hovercraft Full Of Eels Avatar answered Mar 06 '23 16:03

Hovercraft Full Of Eels