Get current active window's title in Java

Steven picture Steven · Aug 30, 2009 · Viewed 23k times · Source

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.

Answer

Matthew Phillips picture Matthew Phillips · Apr 1, 2010

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.