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

kyosohma at gmail.com kyosohma at gmail.com
Tue Dec 25 14:27:12 EST 2007


On Dec 25, 4:31 am, mangoldproj... at gmail.com wrote:
> Hi everyone,
>
> 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.
> Your help is greatly appreciated. Thanks!
>
> Assaf.

What you most likely want to do is run the win32gui call inside an
infinite loop. Something along these lines:

# untested code
import time
while True:
   winTitle = GetWindowText(GetForegroundWindow())
   if winTitle == 'some string':
       # do something
   time.sleep(1) # nap for a second


This will check once a second to see what window you have up. You'll
probably want to set some kind of sentinel value when it does
something to the current window so it doesn't repeatedly do that
something each second. Thus, the if-then logic will need to be more
complex, but this should get you going.

HTH

Mike



More information about the Python-list mailing list