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

后端 未结 9 1794
走了就别回头了
走了就别回头了 2020-11-28 08:04

I\'m implementing a task-bar replacement, dock-like application-switcher style program. It\'s doing some unique stuff with OpenGL, and with keyboard shortcuts, so the way it

9条回答
  •  伪装坚强ぢ
    2020-11-28 08:40

    This answer builds on @nspire and @nergeia above, and wraps in a method to find the window handle (https://www.blog.pythonlibrary.org/2014/10/20/pywin32-how-to-bring-a-window-to-front/) into one convenience function:

    def raise_window(my_window):
    
        import win32con
        import win32gui
    
        def get_window_handle(partial_window_name):
    
            # https://www.blog.pythonlibrary.org/2014/10/20/pywin32-how-to-bring-a-window-to-front/
    
            def window_enumeration_handler(hwnd, windows):
                windows.append((hwnd, win32gui.GetWindowText(hwnd)))
    
            windows = []
            win32gui.EnumWindows(window_enumeration_handler, windows)
    
            for i in windows:
                if partial_window_name.lower() in i[1].lower():
                    return i
                    break
    
            print('window not found!')
            return None
    
        # https://stackoverflow.com/questions/6312627/windows-7-how-to-bring-a-window-to-the-front-no-matter-what-other-window-has-fo
    
        def bring_window_to_foreground(HWND):
            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)
    
        hwnd = get_window_handle(my_window)
    
        if hwnd is not None:
            bring_window_to_foreground(hwnd[0])
    
    
    raise_window('Untitled - notepad')
    

提交回复
热议问题