views:

1436

answers:

5

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.

A: 

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;
}

this is from here More clues on Window state here.

Kevin Boyd
That only takes Java windows into account, though, whereas I think Steven wants to get the globally active window, whether it's a Java program or not.
David Zaslavsky
Oops! I misunderstood the question!
Kevin Boyd
David is right, I want to know the name of the globally active window. That way I can automatically keep track of when I use, say, firefox, and when I use, say, Eclipse.
Steven
Is this Java SE or Java ME code?
Jenko
A: 

Have you written your program? Is it shared?

Post stuff like this as comments.
Chinmay Kanchi
Don't you need a certain number of points to comment?
Brendan Long
+1  A: 

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.

Matthew Phillips
A: 

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.

A: 

If you find the right AppleScript, you can use this java library to call it:

http://ivolo.mit.edu/post/ApplePie-Use-Java-to-Run-AppleScript-and-Control-your-Mac-and-Applications.aspx

Ilya