Overview
This is a method to get the current screen size (resolution) and the current mouse cursor coordinates using the GUI automation library “PyAutoGUI.” This is a fundamental implementation for identifying click positions and detecting screen edges when creating automation scripts.
Specifications
- Input: None (retrieves display information and mouse state from the execution environment).
- Output:
- Screen width and height (integers).
- Mouse X and Y coordinates (integers).
- Result of checking if specific coordinates are on the screen (boolean).
- Prerequisite: Installation of the external library
pyautogui. - Command:
pip install pyautogui
Basic Usage
This is the most basic code to get the overall screen size and the current mouse position.
import pyautogui
# Get screen size
screen_width, screen_height = pyautogui.size()
print(f"Screen size: Width {screen_width}px, Height {screen_height}px")
# Get mouse coordinates
current_x, current_y = pyautogui.position()
print(f"Current location: X={current_x}, Y={current_y}")
Full Code Example
This implementation includes screen information retrieval and logic to determine if specified coordinates are within the screen range. It is designed for practical use, including error handling.
import pyautogui
import sys
def analyze_screen_status():
"""
Retrieves current screen resolution and mouse position, and displays information.
Also verifies if target coordinates are within the screen range.
"""
try:
# 1. Get screen resolution
# pyautogui.size() returns a named tuple (width, height)
width, height = pyautogui.size()
# 2. Get current mouse coordinates
# pyautogui.position() returns a named tuple (x, y)
x, y = pyautogui.position()
print("--- Screen Information ---")
print(f"Resolution: {width} x {height}")
print(f"Aspect Ratio: {width / height:.2f}")
print("\n--- Mouse Information ---")
print(f"Current Coordinates: (X: {x}, Y: {y})")
# 3. Check coordinate range (onScreen)
# Example: Check if a fixed target coordinate is within the screen
target_x, target_y = 1920, 1080 # Coordinates for testing
is_inside = pyautogui.onScreen(target_x, target_y)
print("\n--- Result ---")
if is_inside:
print(f"Target coordinates ({target_x}, {target_y}) exist on the screen.")
else:
print(f"Target coordinates ({target_x}, {target_y}) are off-screen.")
except pyautogui.PyAutoGUIException as e:
print(f"PyAutoGUI error occurred: {e}")
except Exception as e:
print(f"Unexpected error: {e}")
if __name__ == "__main__":
analyze_screen_status()
Customization Points
- Tuple Unpacking: The return values of
size()andposition()are tuples. Assigning them directly to variables likew, h = pyautogui.size()improves readability for subsequent calculations. - Using onScreen:
pyautogui.onScreen(x, y)returnsTrueorFalsedepending on whether the coordinates are within the valid range. Using this check before a click operation acts as a guard to prevent errors when trying to click off-screen.
Important Notes
- Multi-monitor Environment:
pyautogui.size()only returns the resolution of the primary monitor. When working across multiple monitors, coordinates for secondary monitors may be relative to the primary one (potentially negative values), which can complicateonScreen()checks. - OS Scaling Settings (DPI): If screen scaling (e.g., 125%, 150%) is set on Windows or macOS, the physical pixel count may not match the logical coordinates retrieved by PyAutoGUI. If coordinates are off, you may need to check OS settings or apply a correction value.
- Fail-Safe Feature: By default, PyAutoGUI has a “fail-safe” feature that stops the script if you move the mouse quickly to one of the four corners (like the top-left). Be careful with coordinate management to avoid unintended stops.
Application
This is a simple logger that monitors mouse coordinates at regular intervals and outputs a log only when there is movement.
import pyautogui
import time
def monitor_mouse_movement(duration=10):
"""
Monitors mouse movement for a specified number of seconds.
"""
print(f"Monitoring started (for {duration} seconds)...")
start_time = time.time()
last_x, last_y = pyautogui.position()
try:
while time.time() - start_time < duration:
current_x, current_y = pyautogui.position()
# Output only when coordinates change
if (current_x != last_x) or (current_y != last_y):
print(f"Movement detected: ({last_x}, {last_y}) -> ({current_x}, {current_y})")
last_x, last_y = current_x, current_y
# Wait briefly to reduce load
time.sleep(0.1)
except KeyboardInterrupt:
print("\nMonitoring interrupted.")
print("Monitoring finished")
if __name__ == "__main__":
monitor_mouse_movement()
Conclusion
Retrieving screen information with PyAutoGUI is the foundation of automation scripts. Understanding environment boundaries with size() and performing safe coordinate operations by combining position() and onScreen() is the first step toward stable, error-free automation.
