使用 win32gui 居中 window

Using win32gui to center a window

我正在自学如何使用 python 自动化 Windows 应用程序,但遇到了一些小问题。我想打开 calc.exe,将其置于前台,然后将其置于屏幕中央,这样我就可以使用静态坐标来操作计算器。我似乎无法弄清楚为什么 window 不会以 win32gui.MoveWindow 为中心。

如何修改下面的代码以使 window 居中?

#Encapsulates some calls to with Winapi for window management
class WindowMgr:

    #Constructor
    def __init__ (self):
        self._handle = None

    #Find the window by its class name
    def find_window(self, class_name, window_name=None):
        self._handle = win32gui.FindWindow(class_name, window_name)

    #Pass to win32gui.EnumWindows() to check all of the open windows
    def _window_enum_callback(self, hwnd, wildcard):
        if re.match(wildcard, str(win32gui.GetWindowText(hwnd))) is not None:
            self._handle = hwnd

    #Find a window that matches the title of the wildcard regex
    def find_window_wildcard(self, wildcard):
        self._handle = None
        win32gui.EnumWindows(self._window_enum_callback, wildcard)

    #Put the window in the foreground
    def set_foreground(self):
        win32gui.SetForegroundWindow(self._handle)

    #Move the window to center screen
    def move_to_center(self):
        w_wid = int(screenWidth/2)
        w_len = int(screenHeight/2)
        win32gui.MoveWindow(self._handle, 0, 0, w_wid, w_len, 0)

w = WindowMgr()
w.find_window_wildcard(".*Calc.*")
w.set_foreground()
w.move_to_center()

我让它工作了,这是我想出来的,以防它有用。

def enumHandler(hwnd, lParam):
    if win32gui.IsWindowVisible(hwnd):
        if 'Calculator' in win32gui.GetWindowText(hwnd):
            win32gui.MoveWindow(hwnd, screenWidth/3, screenHeight/3, 0, 0, True)

win32gui.EnumWindows(enumHandler, None)