I am trying to write a Java program that logs what application I'm using every 5 seconds (this is a time tracker app). I need some way to find out what the current active window is. I found KeyboardFocusManager.getGlobalActiveWindow() but I can't get it to work right. A cross platform solution is preferable, but if one doesn't exist, then I'm developing for linux with X.Org. Thanks.
To find the active Window(be it a frame or a dialog) in a java swing application you can use the following recursive method:
Window getSelectedWindow(Window[] windows) {
Window result = null;
for (int i = 0; i < windows.length; i++) {
Window window = windows[i];
if (window.isActive()) {
result = window;
} else {
Window[] ownedWindows = window.getOwnedWindows();
if (ownedWindows != null) {
result = getSelectedWindow(ownedWindows);
}
}
}
return result;
}
I'm quite certain that you'll find there's no way to enumerate the active windows in pure Java (I've looked pretty hard before), so you'll need to code for the platforms you want to target.
On Mac OS X, you can launch an AppleScript using "osascript".
On X11, you can use xwininfo.
On Windows, you can probably launch some VBScript (e.g. this link looks promising).
If you're using SWT, you may be able to find some undocumented, non-public methods in the SWT libs, since SWT provides wrappers for a lot of the OS API's (e.g. SWT on Cocoa has the org.eclipse.swt.internal.cocoa.OS#objc_msgSend()
methods that can be used to access the OS). The equivalent "OS" classes on Windows and X11 may have API's you can use.
I've written a bash script that logs the current active window: http://www.whitelamp.com/public/active-window-logger.html It uses a patched version of wmctrl but provides details of an alternative (slower) method using xprop and xwininfo.
The links to the wmctrl patch & source code and the script can be found above.
If you find the right AppleScript, you can use this java library to call it: