5

Is there any way to get a list of all windows that are open at present and see what window is at the top (i.e. active?) from Python?

This is using Gnome on Ubuntu Linux.

wnck looks like it might do this, but it's very lacking in documentation.

Matt Joiner
  • 112,946
  • 110
  • 377
  • 526
Amandasaurus
  • 58,203
  • 71
  • 188
  • 248
  • 3
    The [C documentation](http://library.gnome.org/devel/libwnck/stable/) or [Perl documentation](http://gtk2-perl.sourceforge.net/doc/pod/Gnome2/Wnck/index.html) is probably what you need. The Python is not very different. – Josh Lee Feb 08 '11 at 16:57
  • See [Obtain Active window using Python](http://stackoverflow.com/a/36419702/562769) – Martin Thoma Apr 05 '16 at 07:31

2 Answers2

12

Here's the same code using the modern GObject Introspection libraries instead of the now deprecated PyGTK method Josh Lee posted:

from gi.repository import Gtk, Wnck

Gtk.init([])  # necessary if not using a Gtk.main() loop
screen = Wnck.Screen.get_default()
screen.force_update()  # recommended per Wnck documentation

window_list = screen.get_windows()
active_window = screen.get_active_window()

As for documentation, check out the Libwnck Reference Manual. It is not specific for python, but the whole point of using GObject Introspection is to have the same API across all languages, thanks to the gir bindings.

Also, Ubuntu ships with both wnck and its corresponding gir binding out of the box, but if you need to install them:

sudo apt-get install libwnck-3-* gir1.2-wnck-3.0

This will also install libwnck-3-dev, which is not necessary but will install useful documentation you can read using DevHelp

MestreLion
  • 12,698
  • 8
  • 66
  • 57
8
import wnck
screen = wnck.screen_get_default()
window_list = screen.get_windows()
active_window = screen.get_active_window()

See also Get active window title in X, and WnckScreen in the documentation. Other questions containing wnck have useful code samples.

Community
  • 1
  • 1
Josh Lee
  • 171,072
  • 38
  • 269
  • 275
  • 3
    Please note that this will always return the same window when queried repeatedly, even when that window is no longer active. To update the state, you have to flush the Gtk event queue and call `force_update` explicitly before calling `get_active_window`. Look at this gist for an example: https://gist.github.com/adewes/6960581 – ThePhysicist Oct 13 '13 at 10:19