python 前置程序窗口,还原最小化的窗口

python 前置程序窗口,还原最小化的窗口

在网上找了比较久,大多是:

win32gui.FindWindow(class_name, window_name)

win32gui.SetForegroundWindow(self._handle)

这样只会高亮那个窗口,并不会还原大小,下面是根据参考修改得来的:https://stackoverflow.com/questions/38529064/how-can-i-bring-a-window-to-the-foreground-using-win32gui-in-python-even-if-the

import win32gui, win32con
import re

class WindowMgr:
    """Encapsulates some calls to the winapi for window management"""
    def __init__ (self):
        """Constructor"""
        self._handle = None

    def find_window(self, class_name, window_name = None):
        """find a window by its class_name"""
        self._handle = win32gui.FindWindow(class_name, window_name)

    def _window_enum_callback(self, hwnd, wildcard):
        '''Pass to win32gui.EnumWindows() to check all the opened windows'''
        if re.match(wildcard, str(win32gui.GetWindowText(hwnd))) != None:
            self._handle = hwnd

    def find_window_wildcard(self, wildcard):
        self._handle = None
        win32gui.EnumWindows(self._window_enum_callback, wildcard)

    def set_foreground(self):
        """put the window in the foreground"""
        done = False
        if self._handle > 0:
            win32gui.SendMessage(self._handle, win32con.WM_SYSCOMMAND, win32con.SC_RESTORE, 0)
            win32gui.SetForegroundWindow(self._handle)
            done = True
        return done
        
if __name__ == '__main__':
    w = WindowMgr()
    w.find_window_wildcard(".*Notepad.*")
    w.set_foreground()    

主要添加了 

win32gui.SendMessage(self._handle, win32con.WM_SYSCOMMAND, win32con.SC_RESTORE, 0)
posted @ 2019-07-12 14:52  ibingshan  阅读(5596)  评论(1编辑  收藏  举报