Dev-Picayune

picayune: of little value or importance

Python and win32: Bring a Window to Front or Top

Oh joy! I had the need to bring a window (other than my own program) to the front or top, even if it was minimized. So after looking around for awhile, I pieced together several different things and managed to accomplish what I needed with the following code:

import win32api import win32con import win32gui  def windowEnumerationHandler(hwnd, resultList):     '''Pass to win32gui.EnumWindows() to generate list of window handle, window text tuples.'''     resultList.append((hwnd, win32gui.GetWindowText(hwnd)))  def bringToFront(windowText):     topWindows = []     win32gui.EnumWindows(windowEnumerationHandler, topWindows)     print len(topWindows)     for i in topWindows:         if i[1] and windowText.lower() in i[1].lower():             print i[1]             win32gui.ShowWindow(i[0],5)             win32gui.SetForegroundWindow(i[0])

The important stuff here is the callback function and the win32 calls. Also note that it appears that we need both the ShowWindow call and the SetForegroundWindow call. The ShowWindow handles minimized windows and the SetForegroundWindow call pulls it it to the top. I’ll be the first to admit this isn’t really good code. There are other ways of getting window handles. This just happens to be the method that I got to work.

1 comment

1 Comment so far

  1. robin lee August 1st, 2009 9:12 am

    Dear ScW

    The last 2 lines are the important ones,
    which were:
    win32gui.ShowWindow(hwnd,win32con.SW_SHOW)
    win32gui.SetForegroundWindow(hwnd)
    Your constant of 5 equates to constant SW_SHOW which many MFC programmers will probably recognize
    and hwnd is the ubiquitous window’s handle

    I tested this under vista, and python 2.5

Leave a reply

For spam filtering purposes, please copy the number 4816 to the field below: