[python-win32] How can I detect when a user switches between windows?

Assaf Tal mangoldproject at gmail.com
Thu Dec 27 19:10:35 CET 2007


Hi everybody,

I hope I've come to the right place :).
My name is Assaf, and I'm trying to write a small Python utility on a Win-XP
platform. I'm not a beginning programmer (having experience mainly with
scientific computations), but I'm pretty new to Python and Windows
programming.
The utility will execute a set of commands whenever the user switches his
focus between different windows, including child windows in MDI applications
(e.g. between two photos in Photoshop), based on the title of the window
switched to.
I've already figured how to retrieve an active window's title, by using
win32gui's GetWindowText(GetForegroundWindow()). However, I'm still trying
to figure out the best way of detecting whenever the focus shifts between
windows. For my purposes, "shifting the focus" is equivalent to having the
window's blue title bar become active.
I've asked around and been given two ways of doing this, but both seem very
unnatural:
1.) Using some timer, run a check every x seconds to see whether the
window's title has changed, and act accordingly. This seems clumsy.
2.) Use PyHook and perhaps see when the keyboard focus has changed (not sure
how to do that one yet, though). This seems like a decent solution (assuming
I'll get it to work), but I can easily think of situations in which keyboard
focus and window focus are not the same. For example, in many video and
audio editing programs, one can switch between multiple open windows and
still have his/her keyboard control the "mother application".
So basically what I'm asking is: is there an elegant solution to this
problem? Can I "bind" somehow a window-switching event, perhaps directly via
the underlying windows API or some suitable wrapper?
Your help is very much appreciated, and please let me know if I've picked
the wrong group for this and there is some more suitable place to ask this
question.
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/python-win32/attachments/20071227/e9b352ad/attachment.htm 


More information about the python-win32 mailing list