CtrlK
BlogDocsLog inGet started
Tessl Logo

tessl/pypi-pyautogui

Cross-platform GUI automation library that enables programmatic control of mouse, keyboard, and screen interactions.

Pending

Quality

Pending

Does it follow best practices?

Impact

Pending

No eval scenarios have been run

Overview
Eval results
Files

window-management.mddocs/

Window Management

Window control and management operations for finding, manipulating, and interacting with application windows. These functions provide comprehensive window management capabilities including finding windows by title, getting window information, and controlling window state and position.

Note: Window management functions are primarily supported on Windows platform. Limited functionality may be available on other platforms.

Capabilities

Active Window Operations

Get information about and interact with the currently active (focused) window.

def getActiveWindow():
    """
    Get the currently active (focused) window.
    
    Returns:
    Window: Window object representing the active window, or None if no active window
    
    Platform: Windows (primary support), limited macOS/Linux support
    """

def getActiveWindowTitle():
    """
    Get the title of the currently active window.
    
    Returns:
    str: Title of the active window, or None if no active window
    
    Platform: Windows (primary support), limited macOS/Linux support
    """

Window Discovery

Find windows by various criteria including title, position, and other attributes.

def getWindowsAt(x, y):
    """
    Get all windows at the specified screen coordinates.
    
    Parameters:
    - x, y (int): Screen coordinates
    
    Returns:
    List[Window]: List of Window objects at the specified position
    
    Platform: Windows only
    """

def getWindowsWithTitle(title):
    """
    Get all windows with the specified title (exact match).
    
    Parameters:
    - title (str): Exact window title to match
    
    Returns:
    List[Window]: List of Window objects with matching title
    
    Platform: Windows (primary), limited macOS/Linux support
    
    Example:
    notepad_windows = pyautogui.getWindowsWithTitle('Notepad')
    if notepad_windows:
        notepad_windows[0].activate()
    """

def getAllWindows():
    """
    Get all visible windows on the desktop.
    
    Returns:
    List[Window]: List of all Window objects
    
    Platform: Windows (primary), limited macOS/Linux support
    """

def getAllTitles():
    """
    Get titles of all visible windows.
    
    Returns:
    List[str]: List of window titles
    
    Platform: Windows (primary), limited macOS/Linux support
    """

Window Class

The Window class provides methods and properties for interacting with individual windows.

class Window:
    """
    Represents a window on the desktop with methods for manipulation and property access.
    
    Platform: Windows (full support), limited macOS/Linux support
    """
    
    # Window Properties
    @property
    def title(self):
        """str: Window title text"""
    
    @property  
    def left(self):
        """int: Left edge X coordinate of window"""
    
    @property
    def top(self):
        """int: Top edge Y coordinate of window"""
    
    @property
    def right(self):
        """int: Right edge X coordinate of window"""
    
    @property
    def bottom(self):
        """int: Bottom edge Y coordinate of window"""
    
    @property
    def width(self):
        """int: Window width in pixels"""
    
    @property
    def height(self):
        """int: Window height in pixels"""
    
    @property
    def size(self):
        """Tuple[int, int]: Window size as (width, height)"""
    
    @property
    def topleft(self):
        """Tuple[int, int]: Top-left corner as (x, y)"""
    
    @property
    def topright(self):
        """Tuple[int, int]: Top-right corner as (x, y)"""
    
    @property
    def bottomleft(self):
        """Tuple[int, int]: Bottom-left corner as (x, y)"""
    
    @property
    def bottomright(self):
        """Tuple[int, int]: Bottom-right corner as (x, y)"""
    
    @property
    def center(self):
        """Tuple[int, int]: Window center as (x, y)"""
    
    @property
    def box(self):
        """Tuple[int, int, int, int]: Window bounds as (left, top, width, height)"""
    
    @property
    def area(self):
        """int: Window area in pixels (width * height)"""
    
    @property
    def isMaximized(self):
        """bool: True if window is maximized"""
    
    @property
    def isMinimized(self):
        """bool: True if window is minimized"""
    
    @property
    def isActive(self):
        """bool: True if window is currently active/focused"""
    
    @property
    def visible(self):
        """bool: True if window is visible"""
    
    # Window Control Methods
    def activate(self):
        """
        Bring window to front and give it focus.
        
        Returns:
        None
        """
    
    def close(self):
        """
        Close the window.
        
        Returns:
        None
        """
    
    def minimize(self):
        """
        Minimize the window.
        
        Returns:
        None
        """
    
    def maximize(self):
        """
        Maximize the window.
        
        Returns:
        None
        """
    
    def restore(self):
        """
        Restore window from minimized or maximized state.
        
        Returns:
        None
        """
    
    def resize(self, width, height):
        """
        Resize the window to specified dimensions.
        
        Parameters:
        - width, height (int): New window dimensions in pixels
        
        Returns:
        None
        """
    
    def resizeRel(self, widthOffset, heightOffset):
        """
        Resize window relative to current size.
        
        Parameters:
        - widthOffset, heightOffset (int): Relative size changes in pixels
        
        Returns:
        None
        """
    
    def resizeTo(self, width, height):
        """Alias for resize() - resize window to absolute dimensions."""
    
    def moveTo(self, x, y):
        """
        Move window to absolute screen position.
        
        Parameters:
        - x, y (int): New top-left corner coordinates
        
        Returns:
        None
        """
    
    def moveRel(self, xOffset, yOffset):
        """
        Move window relative to current position.
        
        Parameters:
        - xOffset, yOffset (int): Relative movement in pixels
        
        Returns:
        None
        """

Usage Examples

import pyautogui
import time

# Get active window information
active_window = pyautogui.getActiveWindow()
if active_window:
    print(f"Active window: {active_window.title}")
    print(f"Position: ({active_window.left}, {active_window.top})")
    print(f"Size: {active_window.width} x {active_window.height}")

# Find specific application windows
notepad_windows = pyautogui.getWindowsWithTitle('Untitled - Notepad')
if notepad_windows:
    notepad = notepad_windows[0]
    print(f"Found Notepad at: {notepad.topleft}")
    notepad.activate()  # Bring to front
else:
    print("Notepad not found")

# Work with multiple windows of same application
chrome_windows = pyautogui.getWindowsWithTitle('Google Chrome')
for i, window in enumerate(chrome_windows):
    print(f"Chrome window {i+1}: {window.title}")
    
# Get all window titles
all_titles = pyautogui.getAllTitles()
print("All open windows:")
for title in all_titles:
    print(f"  - {title}")

# Window manipulation
def organize_windows():
    """Organize all windows in a grid pattern"""
    windows = pyautogui.getAllWindows()
    screen_width, screen_height = pyautogui.size()
    
    # Calculate grid dimensions
    num_windows = len(windows)
    cols = int(num_windows ** 0.5) + 1
    rows = (num_windows + cols - 1) // cols
    
    window_width = screen_width // cols
    window_height = screen_height // rows
    
    for i, window in enumerate(windows):
        if window.visible and not window.isMinimized:
            col = i % cols
            row = i // cols
            
            x = col * window_width
            y = row * window_height
            
            window.moveTo(x, y)
            window.resize(window_width - 10, window_height - 10)  # Small gap

# Window state management
def manage_window_state(window_title):
    """Demonstrate window state management"""
    windows = pyautogui.getWindowsWithTitle(window_title)
    if not windows:
        print(f"Window '{window_title}' not found")
        return
    
    window = windows[0]
    
    # Show window properties
    print(f"Window: {window.title}")
    print(f"Maximized: {window.isMaximized}")
    print(f"Minimized: {window.isMinimized}")
    print(f"Active: {window.isActive}")
    print(f"Visible: {window.visible}")
    
    # Demonstrate state changes
    window.activate()
    time.sleep(1)
    
    if window.isMaximized:
        window.restore()
        time.sleep(1)
    
    window.maximize()
    time.sleep(1)
    
    window.minimize()
    time.sleep(1)
    
    window.restore()

# Find and interact with windows at specific coordinates
def click_window_at_position(x, y):
    """Find and activate window at screen coordinates"""
    windows_at_pos = pyautogui.getWindowsAt(x, y)
    if windows_at_pos:
        top_window = windows_at_pos[0]  # Get topmost window
        print(f"Found window at ({x}, {y}): {top_window.title}")
        top_window.activate()
        return top_window
    else:
        print(f"No window found at ({x}, {y})")
        return None

# Advanced window searching
def find_window_by_partial_title(partial_title):
    """Find windows with titles containing the specified text"""
    all_windows = pyautogui.getAllWindows()
    matching_windows = []
    
    for window in all_windows:
        if partial_title.lower() in window.title.lower():
            matching_windows.append(window)
    
    return matching_windows

# Example usage
chrome_windows = find_window_by_partial_title('Chrome')
for window in chrome_windows:
    print(f"Found Chrome window: {window.title}")

# Window positioning and sizing
def center_window(window_title, width=800, height=600):
    """Center a window on screen with specified size"""
    windows = pyautogui.getWindowsWithTitle(window_title)
    if not windows:
        return False
    
    window = windows[0]
    screen_width, screen_height = pyautogui.size()
    
    # Calculate center position
    x = (screen_width - width) // 2
    y = (screen_height - height) // 2
    
    window.moveTo(x, y)
    window.resize(width, height)
    window.activate()
    return True

# Use the function
if center_window('Calculator', 400, 500):
    print("Calculator centered successfully")
else:
    print("Calculator window not found")

# Monitor window changes
def monitor_active_window(duration=10):
    """Monitor active window changes for specified duration"""
    print(f"Monitoring active window for {duration} seconds...")
    last_title = ""
    start_time = time.time()
    
    while time.time() - start_time < duration:
        current_title = pyautogui.getActiveWindowTitle()
        if current_title != last_title:
            print(f"Active window changed to: {current_title}")
            last_title = current_title
        time.sleep(0.5)

# Run monitoring
monitor_active_window(30)

Platform-Specific Notes

Windows

  • Full functionality available
  • Uses PyGetWindow library for comprehensive window management
  • Supports all window properties and methods
  • Works with all window types including system dialogs

macOS

  • Limited functionality through PyObjC
  • Basic window detection and activation
  • Some properties may not be available
  • Performance may be slower than Windows

Linux

  • Basic functionality through X11
  • Window detection and simple operations
  • Advanced features may not work consistently
  • Depends on window manager capabilities

Error Handling

# Safe window operations with error handling
def safe_window_operation(window_title, operation):
    """Safely perform window operations with error handling"""
    try:
        windows = pyautogui.getWindowsWithTitle(window_title)
        if not windows:
            print(f"Window '{window_title}' not found")
            return False
        
        window = windows[0]
        
        if operation == 'activate':
            window.activate()
        elif operation == 'maximize':
            window.maximize()
        elif operation == 'minimize':
            window.minimize()
        elif operation == 'close':
            window.close()
        
        return True
        
    except Exception as e:
        print(f"Error performing {operation} on {window_title}: {e}")
        return False

# Use safe operations
safe_window_operation('Notepad', 'activate')
safe_window_operation('Calculator', 'maximize')

Dependencies

Window management functionality requires the PyGetWindow library:

pip install pygetwindow

This dependency is automatically installed with PyAutoGUI on Windows but may need separate installation on other platforms.

Install with Tessl CLI

npx tessl i tessl/pypi-pyautogui

docs

index.md

keyboard-input.md

message-boxes.md

mouse-control.md

screen-image.md

utilities.md

window-management.md

tile.json