8

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?

Erigami
  • 4,476

6 Answers6

6

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).

4

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.

frabjous
  • 6,431
  • 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
4

try using the wnck lib and then use this code:

import wnck
import gtk

while True:
if __name__ == '__main__':
    screen = wnck.screen_get_default()
    screen.force_update()
    while True:
        while gtk.events_pending():
            gtk.main_iteration()
        #time.sleep(0.5)
        print screen.get_active_window().get_name()
akazuko
  • 205
  • 2
  • 9
3

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

RAOF
  • 11,769
2

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
Oli
  • 293,335
1

From info xtool:

getactivewindow
   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"
Peter.O
  • 24,681