[python-win32] Confusion with 'SetForegroundWindow()

Scott Nelson sirgnip at gmail.com
Mon Mar 17 18:09:32 CET 2008


Greets...

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.

In simple cases win32gui.SetForegroundWindow(hwnd) seems to be what
I'm looking for.  It works fine when I simply try to set focus to
another window from my app.

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?  Do I have some bad assumptions?
Is my app allowed to "give away" its focus but can't force a different
app's window with focus to "give away" its focus?  Is there any other
way to accomplish this?  I've attempted using a mix of SetFocus(),
BringWindowToTop(), and EnableWindow() but couldn't find a magic
combo.

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.  Run it as "WinTests 12345" to successfully set the focus
to the window with hwnd of 12345.  Run it as "WinTests" to get a list
of all top level window names and their hwnd's.

I've tried reading the win32 docs provided with ActiveState's
PythonWin, I've read a bit on the win32 API on MSDN and I've googled
around a bit, and haven't found much.

So, I got curious and tried to code up something similar in C++.  It
uses the identical API calls (from what I can tell) and It seems to
have no problem cycling through all the top-level windows.  I've
attached my .cpp file as well.

Why the discrepancy between what I'm seeing with win32gui and c++?  Thoughts?

-Scott
-------------- next part --------------
An embedded and charset-unspecified text was scrubbed...
Name: SetForegroundWindow.cpp
Url: http://mail.python.org/pipermail/python-win32/attachments/20080317/b29565b5/attachment.txt 
-------------- next part --------------
An embedded and charset-unspecified text was scrubbed...
Name: WinTests.py
Url: http://mail.python.org/pipermail/python-win32/attachments/20080317/b29565b5/attachment-0001.txt 


More information about the python-win32 mailing list