How to detect when a user switches between windows (in WinXP)?

Tim Roberts timr at probo.com
Thu Dec 27 01:12:24 EST 2007


mangoldproject at gmail.com wrote:
>
>I'm a beginning-to-intermediate Python programmer with some experience
>in other languages. At the moment I am trying to write a Python
>program that will run in the background and execute a series of
>commands whenever I switch between windows (my OS is Windows XP). For
>example, I want my program to do something when I switch to my Firefox
>browser, and then do something else when I switch to a certain sub-
>window in Photoshop (which has a certain title, and a certain photo
>associated with it), then do yet another thing when I switch to
>another sub-window (with a different title and photo) within
>Photoshop.
>The particular actions will be based on the window's title. I've
>already figured out how to retrieve that, using
>GetWindowText(GetForegroundWindow()) from the win32gui module.
>My question is, how can I detect when the user switches between
>windows? I haven't been able to figure that part out yet.
>Searching the group didn't give me any answers.

The way you do this is to write a Windows hook.  The WH_CBT hook intercepts
WM_ACTIVATE and WM_DEACTIVATE calls system-wide.

However, that requires injecting the hook DLL into every process with a
Windows, and you certainly don't want to do that in Python.  Write a
minimal C DLL to be the hook, and have it send messages to your Python
process.
-- 
Tim Roberts, timr at probo.com
Providenza & Boekelheide, Inc.



More information about the Python-list mailing list