Windows 7: how to bring a window to the front no matter what other window has focus?

I don't like these suggestions of using win32gui because you can't easily install that via pip. So here's my solution:

First, install pywinauto via pip. If you're on Python 2.7.9 or a newer version on the 2 branch, or Python 3.4.0 or a newer version from the 3 branch, pip is already installed. For everyone else, update Python to get it (or you can manually download and install it by running this script, if you must run an older version of Python.)

Just run this from the command line (not from within Python):

pip install pywinauto

Next, import what you need from pywinauto:

from pywinauto.findwindows    import find_window
from pywinauto.win32functions import SetForegroundWindow

Finally, it's just one actual line:

SetForegroundWindow(find_window(title='taskeng.exe'))

I've had some code that's been running for years, going all the way back to Windows 95. When double clicking the applications system tray icon I always used Win32 API functions such as BringWindowToTop and SetForegroundWindow to bring my application windows to the foreground. This all stopped working as intended on Windows 7, where my input window would end up behind other windows and the window icon would flash on the status bar. The 'work around' that I came up with was this; and it seems to work on all versions of Windows.

//-- show the window as you normally would, and bring window to foreground.
//   for example;
::ShowWindow(hWnd,SW_SHOW); 
::BringWindowToTop(hWnd);
::SetForegroundWindow(hWnd);

//-- on Windows 7, this workaround brings window to top
::SetWindowPos(hWnd,HWND_NOTOPMOST,0,0,0,0, SWP_NOMOVE | SWP_NOSIZE);
::SetWindowPos(hWnd,HWND_TOPMOST,0,0,0,0,SWP_NOMOVE | SWP_NOSIZE);
::SetWindowPos(hWnd,HWND_NOTOPMOST,0,0,0,0,SWP_SHOWWINDOW | SWP_NOMOVE | SWP_NOSIZE);

According to nspire, I've tried his solution with python 2.7 and W8, and it works like a charm, even if the window is minimized *.

win32gui.ShowWindow(HWND, win32con.SW_RESTORE)
win32gui.SetWindowPos(HWND,win32con.HWND_NOTOPMOST, 0, 0, 0, 0, win32con.SWP_NOMOVE + win32con.SWP_NOSIZE)  
win32gui.SetWindowPos(HWND,win32con.HWND_TOPMOST, 0, 0, 0, 0, win32con.SWP_NOMOVE + win32con.SWP_NOSIZE)  
win32gui.SetWindowPos(HWND,win32con.HWND_NOTOPMOST, 0, 0, 0, 0, win32con.SWP_SHOWWINDOW + win32con.SWP_NOMOVE + win32con.SWP_NOSIZE)
  • Originally it was if the window it's not minimized, but thanks to Whome's comment win32gui.ShowWindow(HWND, win32con.SW_RESTORE), it now works in all situations .