[python-win32] Confusion with 'SetForegroundWindow()

Tim Roberts timr at probo.com
Mon Mar 17 19:41:35 CET 2008


Scott Nelson wrote:
> I'm looking to use the win32api and win32gui modules to do a bit of
> Windows tinkering (win2k, ActiveState's Python 2.4.1 distribution) and
> I've hit a snag.
>
> I'd like to have my process/window "steal" the focus from whatever
> window currently has it, get a bit of input from the keyboard, and
> then restore the focus back to the original window.
> ...
> But, I'm seeing unexpected behavior when I go beyond that.  I wrote a
> simple test script that enumerates through all visible windows and
> tries to give each one the focus in turn, after a short delay.  It
> gets through 1-2 windows out of the 8-10 non-minimized windows I have
> open (IE, notepad, wordpad, etc.) and then gives me this:
>
> Traceback (most recent call last):
>  File "D:\_code\python\apps\WinTests.py", line 25, in ?
>    cycle_foreground()
>  File "D:\_code\python\apps\WinTests.py", line 20, in cycle_foreground
>    win32gui.SetForegroundWindow(handle)
> pywintypes.error: (0, 'SetForegroundWindow', 'No error message is available')
>
> What am I doing wrong in this case?  ...
>
> I've attached my test script.  Run it as "WinTests cycle" to attempt
> to cycle the focus through all top level windows and see the
> traceback.

Your test runs to completion without error on my XP machine.  Is it 
always the same window that causes it to explode?  You didn't say what 
window it is.  It is possible that there are some applications that do 
not want to become foreground unless it was their idea.  
SetForegroundWindow sends a WM_ACTIVATE message, and the application can 
veto the suggestion.  Also, an application can call 
LockSetForegroundWindow to prevent another application from "stealing" 
the focus away.

You may simply need to trap this error.

-- 
Tim Roberts, timr at probo.com
Providenza & Boekelheide, Inc.



More information about the python-win32 mailing list