如何用Python修改Windows分辨率缩放比例并自动恢复?
解决Windows缩放比例影响PyAutoGui图像识别的实现方案
核心思路
通过Windows API和注册表操作,临时将系统显示缩放切换为100%以保证PyAutoGui图像识别的准确性,完成操作后恢复原缩放设置。以下是具体实现代码:
代码实现
import ctypes import pyautogui import time import winreg import subprocess from ctypes import wintypes # 加载Windows系统API user32 = ctypes.WinDLL('user32', use_last_error=True) gdi32 = ctypes.WinDLL('gdi32', use_last_error=True) # 定义API所需数据结构 class POINT(ctypes.Structure): _fields_ = [("x", wintypes.LONG), ("y", wintypes.LONG)] # 获取当前主显示器的缩放比例(百分比) def get_current_scaling(): # 获取主显示器句柄 point = POINT(0, 0) hmonitor = user32.MonitorFromPoint(point, 0x00000001) # 获取设备上下文 hdc = user32.GetDC(None) if not hdc: raise ctypes.WinError(ctypes.get_last_error()) try: # 96 DPI对应100%缩放,计算当前缩放比例 dpi_x = gdi32.GetDeviceCaps(hdc, 88) # LOGPIXELSX return int((dpi_x / 96) * 100) finally: user32.ReleaseDC(None, hdc) # 设置显示器缩放比例(仅支持单显示器,传入百分比数值如100、125) def set_scaling(scaling_percent): target_dpi = int((scaling_percent / 100) * 96) # 设置进程DPI感知,确保后续操作生效 SYSTEM_DPI_AWARENESS_CONTEXT = wintypes.HANDLE(-2) user32.SetProcessDpiAwarenessContext.argtypes = [wintypes.HANDLE] user32.SetProcessDpiAwarenessContext.restype = wintypes.HANDLE user32.SetProcessDpiAwarenessContext(SYSTEM_DPI_AWARENESS_CONTEXT) # 修改注册表项 reg_path = r"Control Panel\Desktop" with winreg.OpenKey(winreg.HKEY_CURRENT_USER, reg_path, 0, winreg.KEY_WRITE) as key: winreg.SetValueEx(key, "LogPixels", 0, winreg.REG_DWORD, target_dpi) # 重启资源管理器使设置生效 subprocess.run(["taskkill", "/f", "/im", "explorer.exe"], check=True, capture_output=True) subprocess.run(["explorer.exe"], check=True) time.sleep(2) # 等待资源管理器重启完成 # 主执行流程 if __name__ == "__main__": # 1. 获取并保存原缩放比例 original_scaling = get_current_scaling() print(f"原缩放比例:{original_scaling}%") try: # 2. 切换到100%缩放 if original_scaling != 100: set_scaling(100) print("已切换到100%缩放") # 3. 执行核心业务代码(替换为你的PyAutoGui逻辑) print("执行核心操作...") # 示例代码:查找目标图像并点击 # target_pos = pyautogui.locateCenterOnScreen("target_icon.png", confidence=0.8) # if target_pos: # pyautogui.click(target_pos) time.sleep(3) # 模拟操作耗时 finally: # 4. 恢复原缩放比例 if original_scaling != 100: set_scaling(original_scaling) print(f"已恢复原缩放比例:{original_scaling}%") print("程序结束")
注意事项
- 代码仅适用于Windows系统,需以管理员权限运行(否则无法修改注册表)
- 重启资源管理器会导致桌面短暂刷新,属于正常现象
- 多显示器环境需修改代码适配特定显示器,当前默认处理主显示器
- PyAutoGui图像识别建议开启
confidence参数(需提前安装opencv-python:pip install opencv-python),提升识别稳定性
内容的提问来源于stack exchange,提问作者Linascts
相关产品推荐
相关产品推荐

