杰瑞科技汇

Python SetWindowPos如何调整窗口位置大小?

Of course! The term SetWindowPos in Python refers to calling the Windows API function of the same name. This function is used to change the size, position, and Z-order (stacking order) of a window.

Python SetWindowPos如何调整窗口位置大小?-图1
(图片来源网络,侵删)

In Python, you don't call this function directly. Instead, you use a library that wraps the Windows API. The most common and user-friendly library for this task is pywin32.

Here's a complete guide on how to use SetWindowPos in Python.


Prerequisites: Install pywin32

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

pip install pywin32

The Core Function: win32gui.SetWindowPos

The function we'll use is win32gui.SetWindowPos. Here's its signature:

Python SetWindowPos如何调整窗口位置大小?-图2
(图片来源网络,侵删)
win32gui.SetWindowPos(
    hWnd,           # The handle to the window to be changed
    hWndInsertAfter,# The handle to the window to precede the positioned window (Z-order)
    X,              # The new x-coordinate (left) of the window
    Y,              # The new y-coordinate (top) of the window
    cx,             # The new width of the window
    cy,             # The new height of the window
    uFlags          # Window positioning flags
)

Understanding the Parameters:

  • hWnd (Window Handle): This is a unique identifier for the window you want to control. You can get it using win32gui.FindWindow() if you know the window's class name or title, or by using a more advanced method like enumerating windows.
  • hWndInsertAfter (Z-Order): This controls the window's position in the stacking order.
    • win32gui.HWND_TOP: Places the window at the top of the Z-order.
    • win32gui.HWND_BOTTOM: Places the window at the bottom of the Z-order.
    • win32gui.HWND_NOTOPMOST: Places the window above all non-topmost windows (but below topmost ones).
    • win32gui.HWND_TOPMOST: Places the window above all non-topmost windows. The window maintains its topmost position even when it is deactivated.
    • Special Value: You can also pass 0 for hWndInsertAfter, which is equivalent to HWND_NOTOPMOST.
  • X, Y (Position): The new coordinates for the top-left corner of the window, in pixels, relative to the top-left corner of the screen.
  • cx, cy (Size): The new width and height of the window, in pixels.
  • uFlags (Flags): A combination of flags that modify the behavior of the function. You can combine these using the bitwise OR operator ().

Common uFlags:

Flag Value Description
SWP_NOSIZE 0x0001 Ignores the cx and cy parameters (does not change the window size).
SWP_NOMOVE 0x0002 Ignores the X and Y parameters (does not change the window position).
SWP_NOZORDER 0x0004 Ignores the hWndInsertAfter parameter (does not change the Z-order).
SWP_NOREDRAW 0x0008 Does not redraw changes.
SWP_NOACTIVATE 0x0010 Does not activate the window.
SWP_SHOWWINDOW 0x0040 Displays the window (if it was hidden).
SWP_HIDEWINDOW 0x0080 Hides the window.

Practical Examples

Let's see how to use this in practice.

Example 1: Moving and Resizing a Known Window (e.g., Notepad)

This example finds the Notepad window by its title and moves it to the top-left corner of the screen, making it 500x400 pixels.

import win32gui
import win32con
def move_notepad():
    # 1. Find the window handle for Notepad
    # The first parameter is the class name (e.g., "Notepad")
    # The second is the window title (e.g., "Untitled - Notepad")
    notepad_hwnd = win32gui.FindWindow("Notepad", None)
    if notepad_hwnd == 0:
        print("Notepad window not found. Please open a Notepad window first.")
        return
    print(f"Found Notepad window with handle: {notepad_hwnd}")
    # 2. Define the new position and size
    x = 100
    y = 100
    width = 500
    height = 400
    # 3. Call SetWindowPos
    # We'll use HWND_TOP to ensure it comes to the front.
    # Flags: SWP_NOZORDER is not needed because we are specifying hWndInsertAfter.
    # We also add SWP_SHOWWINDOW to make sure it's visible.
    flags = win32con.SWP_SHOWWINDOW
    win32gui.SetWindowPos(
        notepad_hwnd,      # Handle to the window
        win32con.HWND_TOP, # Bring it to the top
        x, y,              # New position (x, y)
        width, height,     # New size (width, height)
        flags
    )
    print(f"Moved Notepad to ({x}, {y}) with size {width}x{height}")
# Run the function
move_notepad()

Example 2: Maximizing Any Window

This example demonstrates using flags to change only the Z-order and size, without affecting the position.

import win32gui
import win32con
def maximize_window_by_title(window_title):
    hwnd = win32gui.FindWindow(None, window_title) # Find by title only
    if hwnd == 0:
        print(f"Window titled '{window_title}' not found.")
        return
    print(f"Found window with title '{window_title}' and handle: {hwnd}")
    # To maximize, we need to set the size to the screen size.
    # Get the screen dimensions
    screen_width = win32gui.GetSystemMetrics(0) # SM_CXSCREEN
    screen_height = win32gui.GetSystemMetrics(1) # SM_CYSCREEN
    # Use SWP_NOMOVE to keep the existing position (which is effectively ignored for maximized windows)
    # but it's good practice to include it when you're not changing X/Y.
    flags = win32con.SWP_NOMOVE
    win32gui.SetWindowPos(
        hwnd,
        win32con.HWND_TOP, # Bring to top
        0, 0,              # X, Y (ignored due to SWP_NOMOVE)
        screen_width, screen_height, # Set to screen size
        flags
    )
    print(f"Maximized the window '{window_title}'")
# Example: Maximize the Calculator window (title is "Calculator")
maximize_window_by_title("Calculator")

Example 3: Finding a Window by Partial Title (More Robust)

Sometimes, the full title is dynamic (e.g., includes the file name). It's better to search for a partial match.

Python SetWindowPos如何调整窗口位置大小?-图3
(图片来源网络,侵删)
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():
            # Return the handle to stop the enumeration
            return hwnd
        # Return 0 to continue searching
        return 0
    # Enumerate all top-level windows
    hwnd = win32gui.EnumWindows(callback, None)
    return hwnd
# Example: Find any Chrome window
chrome_hwnd = find_window_by_partial_title("Chrome")
if chrome_hwnd:
    print(f"Found Chrome window with handle: {chrome_hwnd}")
    # Now you can use SetWindowPos on it
    win32gui.SetWindowPos(chrome_hwnd, win32con.HWND_TOP, 50, 50, 800, 600, 0)
    print("Moved Chrome window.")
else:
    print("No Chrome window found.")

Complete Script: A Simple Window Mover

Here is a full, interactive script that lets you enter a window title and move it.

import win32gui
import win32con
import time
def move_window_interactively():
    """Finds a window by title and moves it to a specified position and size."""
    window_title = input("Enter the title of the window to move (e.g., Notepad): ")
    # Find the window by title
    hwnd = win32gui.FindWindow(None, window_title)
    if hwnd == 0:
        print(f"Error: Window with title '{window_title}' not found.")
        return
    print(f"Successfully found window: '{window_title}' (Handle: {hwnd})")
    try:
        x = int(input("Enter new X position (e.g., 100): "))
        y = int(input("Enter new Y position (e.g., 100): "))
        width = int(input("Enter new width (e.g., 600): "))
        height = int(input("Enter new height (e.g., 400): "))
    except ValueError:
        print("Invalid input. Please enter numbers only.")
        return
    print("\nMoving window... (You may need to switch back to the target window)")
    time.sleep(2) # Give the user time to switch back
    # Set the window's position and size
    win32gui.SetWindowPos(
        hwnd,
        win32con.HWND_TOP, # Bring it to the front
        x, y,
        width, height,
        0 # No special flags
    )
    print("Done!")
if __name__ == "__main__":
    move_window_interactively()

Important Considerations

  • Permissions: Your Python script needs sufficient permissions to control the target window. You cannot control windows running as a different user (e.g., Administrator) without running your script with the same elevated privileges.
  • Window State: Some windows (especially games or video players) might have special rendering modes that prevent standard SetWindowPos from working correctly.
  • Dynamic Titles: As seen in Example 3, if the window title changes, your script might fail. Using the window's class name (found with tools like Microsoft Spy++) is often more reliable. FindWindow("Notepad", None) is more robust than FindWindow(None, "Untitled - Notepad").
分享:
扫描分享到社交APP
上一篇
下一篇