杰瑞科技汇

Python中MoveWindow函数如何使用?

Of course! Moving windows with Python is a common task for automation, especially on Windows. The most popular and reliable library for this is pywin32 (also known as pypiwin32).

Python中MoveWindow函数如何使用?-图1
(图片来源网络,侵删)

Here’s a complete guide covering the basics, a practical example, and more advanced scenarios.

The Best Tool for the Job: pywin32

This library is a Python wrapper for the Windows Platform API (Win32 API). It gives you direct, powerful control over windows.

Installation

First, you need to install the library. Open your command prompt or terminal and run:

pip install pywin32

Finding the Window You Want to Move

Before you can move a window, you need to find its unique handle. The easiest way to do this is by the window's title.

Python中MoveWindow函数如何使用?-图2
(图片来源网络,侵删)
  • For exact title matches:

    import win32gui
    window_title = "Untitled - Notepad"
    hwnd = win32gui.FindWindow(None, window_title)
    print(f"Found window handle: {hwnd}")
  • For partial title matches (more robust): If the title might change (e.g., a file path is added), it's better to find windows and check their titles one by one.

    import win32gui
    def find_window_by_partial_title(partial_title):
        def callback(hwnd, extra):
            window_title = win32gui.GetWindowText(hwnd)
            if partial_title.lower() in window_title.lower():
                extra.append(hwnd)
            return True
        hwnds = []
        win32gui.EnumWindows(callback, hwnds)
        return hwnds[0] if hwnds else None
    hwnd = find_window_by_partial_title("Notepad")
    if hwnd:
        print(f"Found window handle: {hwnd}")
    else:
        print("Window not found.")

The Core Functions: MoveWindow and SetWindowPos

Once you have the window's handle (hwnd), you can move it. There are two main functions.

win32gui.MoveWindow(hwnd, x, y, width, height, repaint)

This is a straightforward function. You provide the new coordinates and dimensions.

Python中MoveWindow函数如何使用?-图3
(图片来源网络,侵删)
  • hwnd: The window handle.
  • x, y: The new top-left coordinates of the window.
  • width, height: The new dimensions of the window.
  • repaint: A boolean. If True, the window is redrawn after the move. It's almost always best to leave this as True.

Example:

import win32gui
import time
# Find the Notepad window
hwnd = win32gui.FindWindow(None, "Untitled - Notepad")
if hwnd:
    print("Moving Notepad window...")
    # Move to (100, 100) and resize to 500x400
    win32gui.MoveWindow(hwnd, 100, 100, 500, 400, True)
    print("Done.")
else:
    print("Could not find the Notepad window.")

win32gui.SetWindowPos(hwnd, hWndInsertAfter, x, y, cx, cy, uFlags)

This is a more powerful and flexible function. It's the modern standard and allows you to control things like window stacking order (which window is on top).

  • hwnd: The window handle.
  • hWndInsertAfter: A special constant to control the window's position in the Z-order (stacking order).
    • win32con.HWND_NOTOPMOST: The window remains in its normal position.
    • win32con.HWND_TOP: The window is placed at the top of the Z-order.
    • win32con.HWND_BOTTOM: The window is placed at the bottom of the Z-order.
    • win32con.HWND_TOPMOST: The window is placed above all non-topmost windows. It will maintain its topmost position even when deactivated.
  • x, y: The new position.
  • cx, cy: The new width and height.
  • uFlags: A combination of flags. Common ones are:
    • win32con.SWP_NOSIZE: Ignores the cx and cy parameters (don't change size).
    • win32con.SWP_NOMOVE: Ignores the x and y parameters (don't change position).
    • win32con.SWP_NOZORDER: Ignores the hWndInsertAfter parameter.
    • win32con.SWP_ASYNCWINDOWPOS: Prevents the calling thread from processing any pending requests.

Example:

import win32gui
import win32con
# Find the Notepad window
hwnd = win32gui.FindWindow(None, "Untitled - Notepad")
if hwnd:
    print("Moving and resizing Notepad using SetWindowPos...")
    # Move to (200, 200), resize to 600x400, and make it topmost
    win32gui.SetWindowPos(
        hwnd,
        win32con.HWND_TOPMOST, # Place it on top
        200, 200,             # x, y coordinates
        600, 400,             # width, height
        0                     # No special flags
    )
    print("Done.")
else:
    print("Could not find the Notepad window.")

Complete Practical Example: The Window Mover Script

Let's create a script that finds a window and moves it to the center of the primary monitor.

import win32gui
import win32con
import sys
def get_center_coordinates(hwnd):
    """Calculates the coordinates to center a window on the primary monitor."""
    # Get the dimensions of the primary monitor
    primary_monitor = win32gui.GetMonitorInfo(win32gui.MonitorFromWindow(hwnd, win32con.MONITOR_DEFAULTTOPRIMARY))
    monitor_left = primary_monitor['Monitor'][0]
    monitor_top = primary_monitor['Monitor'][1]
    monitor_width = primary_monitor['Monitor'][2] - monitor_left
    monitor_height = primary_monitor['Monitor'][3] - monitor_top
    # Get the dimensions of the window
    _, _, window_width, window_height = win32gui.GetWindowRect(hwnd)
    # Calculate the new top-left coordinates
    x = monitor_left + (monitor_width - window_width) // 2
    y = monitor_top + (monitor_height - window_height) // 2
    return x, y
def center_window(window_title):
    """Finds a window by title and centers it on the screen."""
    hwnd = win32gui.FindWindow(None, window_title)
    if not hwnd:
        print(f"Error: Window with title '{window_title}' not found.")
        return
    # Check if the window is minimized. If so, restore it first.
    if win32gui.IsIconic(hwnd):
        print("Window is minimized. Restoring it...")
        win32gui.ShowWindow(hwnd, win32con.SW_RESTORE)
    # Get the coordinates to center the window
    x, y = get_center_coordinates(hwnd)
    # Get the current size
    _, _, width, height = win32gui.GetWindowRect(hwnd)
    # Move the window to the center
    print(f"Centering window: {window_title}")
    win32gui.SetWindowPos(hwnd, win32con.HWND_TOP, x, y, width, height, 0)
if __name__ == "__main__":
    if len(sys.argv) > 1:
        # Allow passing the window title as a command-line argument
        window_title = " ".join(sys.argv[1:])
    else:
        # Default to Notepad if no title is provided
        window_title = "Untitled - Notepad"
    center_window(window_title)

How to use this script:

  1. Save the code as center_window.py.
  2. Open Notepad (or another application you want to test with).
  3. Run the script from the command line:
    • To center Notepad: python center_window.py
    • To center a different window (e.g., Calculator): python center_window.py Calculator

Alternative for Linux: pygetwindow

If you're working on Linux, the pygetwindow library is the equivalent. It's a wrapper around the xdotool command-line utility.

Installation

pip install pygetwindow

Example

import pygetwindow as gw
# Find the window by title (case-insensitive)
window_title = "Untitled - Notepad"
window = gw.getWindowsWithTitle(window_title)[0]
if window:
    print(f"Found window: {window.title}")
    # Move to position (100, 100)
    window.moveTo(100, 100)
    # Resize to 600x400
    window.resizeTo(600, 400)
    print("Window moved and resized.")
else:
    print(f"Window with title '{window_title}' not found.")

Summary

Task Windows (pywin32) Linux (pygetwindow)
Find Window win32gui.FindWindow(None, "Title") gw.getWindowsWithTitle("Title")[0]
Get Position/Size win32gui.GetWindowRect(hwnd) window.left, window.top, window.width, window.height
Move Window win32gui.MoveWindow(hwnd, x, y, w, h, True) window.moveTo(x, y)
Resize Window win32gui.MoveWindow(hwnd, x, y, w, h, True) window.resizeTo(w, h)
Bring to Front win32gui.SetWindowPos(hwnd, win32con.HWND_TOP, ...) window.activate()

For Windows development, pywin32 is the undisputed champion for its power and direct access to the system. For quick cross-platform scripts, pygetwindow is an excellent choice.

分享:
扫描分享到社交APP
上一篇
下一篇