开发者

How do I detect the currently focused application?

I'd like to be able to track which application is currently focused on my X11 display from Python. The intent is to tie it into a timetracking tool so that I can keep track of how much time I spend being unproductive.

I already found this code at http://thpinfo.com/2007/09/x11-idle-time-and-focused-window-in.html:

import Xlib.display
display = Xlib.display.Display()
focus = display.get_input_focus()
print "WM Class: %s" % ( focus.focus.get_wm_class(), )
print "WM Name: %s" % ( focus.focus.get_wm_name(), )

However, it doesn't seem to work for me开发者_如何学Python. Apparently, no matter which application is focused, both get_wm_class() and get_wm_name() just return None.

Of course the solution needs to work with all these new fangled window managers like Compiz and such.


Whoo! I figured it out myself:

import Xlib.display
display = Xlib.display.Display()
window = display.get_input_focus().focus
wmname = window.get_wm_name()
wmclass = window.get_wm_class()
if wmclass is None and wmname is None:
    window = window.query_tree().parent
    wmname = window.get_wm_name()
print "WM Name: %s" % ( wmname, )


A somewhat nicer solution, especially for a long-running app rather than a script, would use libwnck to track the _NET_ACTIVE_WINDOW hint. (See the EWMH specification for the definition of the hint.)

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜