为何win32gui.GetCursorPos()坐标需放大1.25倍匹配mss截图?
问题:win32gui.GetCursorPos() 与 mss 截图坐标不匹配
我一直搞不懂为什么win32gui.GetCursorPos()获取的光标坐标,和传入mss用于截图的坐标无法匹配,直到发现前者的坐标被系统压缩了1.25倍。
以下是相关代码(功能:通过两次按下Shift键选择区域,将该区域截图保存为out.png):
import mss import win32api import win32gui import time def get_shift_state(): last = None curr = None pos_array = [] while True: curr = win32api.GetKeyState(160) # 检测Shift键是否按下 if curr < 0 and curr != last: pos = win32gui.GetCursorPos() print(pos) pos_array.append([int(pos[0] * 1.25), int(pos[1] * 1.25)]) # 此处为坐标修正点 if len(pos_array) == 2: break last = curr print(pos_array) return pos_array def take_screenshot(x0, y0, width, height, output='out.png'): with mss.mss() as sct: # 定义要捕获的屏幕区域 monitor = {"top": y0, "left": x0, "width": width, "height": height} sct_img = sct.grab(monitor) mss.tools.to_png(sct_img.rgb, sct_img.size, output=output) def main(): pos_array = get_shift_state() x0 = pos_array[0][0] y0 = pos_array[0][1] x1 = pos_array[1][0] y1 = pos_array[1][1] take_screenshot(x0, y0, x1 - x0, y1 - y0) if __name__ == '__main__': main()
环境信息
- Python 3.11
- pywin32 v306
修复方案
将win32gui.GetCursorPos()获取的坐标值乘以1.25,还原真实屏幕坐标,修正后的关键代码行:
pos_array.append([int(pos[0] * 1.25), int(pos[1] * 1.25)]) # 乘以1.25修正坐标压缩问题
内容的提问来源于stack exchange,提问作者Micael
相关产品推荐
相关产品推荐

