[Tutor] win32gui, SetForegroundWindow() and setting focus

Alan Gauld alan.gauld at btinternet.com
Mon Mar 17 02:32:07 CET 2008


"Scott Nelson" <sirgnip at gmail.com> wrote

> I'd like to programmatically set which window has the focus.  But
> win32gui.SetForegroundWindow(hwnd) seems to be what I'm looking for,
> but, it isn't working quite as I expect meaning I probably have a 
> bad
> assumption.

Thats pretty common with windows API calls :-(

> SetForegroundWindow() works like a charm in simple cases from the
> command line.  However, when I enumerate all top level windows and 
> try

>    win32gui.SetForegroundWindow(handle)
> pywintypes.error: (0, 'SetForegroundWindow', 'No error message is 
> available')
>
> What am I doing wrong in this case?

No idea, but it could be that you don;t have security rights to
some of the processes on your machine - maybe something
in the system tray. Or maybe its a service that doesn't have
a GUI and therefore no Window as such to which it can give
focus. There are several scenarios, none esy to debug and
none well explained in the API docs.

My only advice is probably to only set focus to a known window
don't try setting focus to an arbitrary collection of windows.

> I've tried reading the very-sparse 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.

You are not alone. But thats little comfort I'm sure.

Alan G 




More information about the Tutor mailing list