I'd like to know (programmatically) which window has current focus. Is there a window-manager independent way of discovering that?

Otherwise, how does one determine which window has focus in Compiz or Metacity?


What you want is libwnck (if you're just interested in windows) or libbamf (if you're interested in windows and the applications that own them).

  • 1
    Thanks! This is exactly what I was looking for. It lead me to another question, which was exactly what I was looking for. – Erigami Feb 12 '11 at 1:16

If you're happy doing a little X11 programming, then the EWMH spec is what you're after - specifically _NET_ACTIVE_WINDOW.


Another thing you can use is xdotool:

xdotool getwindowfocus

would return the Window ID of the focussed window, and:

xdotool getwindowfocus getwindowname

would tell you its name.

  • 1
    I get xdotool: Unknown command: getwindowname for the second one. – Oli Feb 10 '11 at 15:41
  • You're using an outdated version of xdotool. The one in the Ubuntu repos is positively ancient, for example. There's a more recent .deb file at their site, for certain architectures, or compile from source if need be. – frabjous Feb 10 '11 at 16:34
  • Not sure about "positively ancient"... My version is 2.20100701.2961, current stable is 2.20101012.3049. 3 months usually doesn't mean that much... But if that's the case, so be it. – Oli Feb 10 '11 at 16:45
  • I was thinking the one in the Lucid LTS repos; Maverick isn't so bad, but apparently it makes a difference here. – frabjous Feb 10 '11 at 16:50

try using the wnck lib and then use this code:

import wnck
import gtk

while True:
if __name__ == '__main__':
    screen = wnck.screen_get_default()
    while True:
        while gtk.events_pending():
        print screen.get_active_window().get_name()

Well if you can ping something back to the shell:

xdpyinfo | grep focus

Should work.

Edit: For slightly cleaner output, try this:

xdpyinfo | grep -Eo 'window 0x[^,]+' | cut -d" " -f2

From info xtool:

   Output the current active window. This command is often more
   reliable than getwindowfocus. The result is saved to the window
   stack. See "WINDOW STACK" for more details.

This is what I use for getting the title. (I an on 10.04)

xwininfo -id "$(xdotool getactivewindow)" |sed -n \
  "2s/^xwininfo: Window id: \(0x[[:xdigit:]]\+\) \x22\(.*\)\x22$/\2/p"

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.