传入坐标x、y直接调用就行了
[Python] 纯文本查看 复制代码
import pyautogui,win32gui
鼠标_单击_模拟用户(坐标x,坐标y)
def 鼠标_单击_模拟用户(x, y, 窗口句柄=None, action=1):
' 模拟用户点击鼠标\n\n 窗口句柄可以不填 action=1表示左键单击,action=2表示双击'
original_pos = pyautogui.position()
try:
if 窗口句柄:
try:
win32gui.SetForegroundWindow(窗口句柄)
except Exception as e:
print(f"无法设置窗口句柄({窗口句柄})为前台窗口:", e)
return False
x_screen, y_screen = win32gui.ClientToScreen(窗口句柄, (x, y))
print(f"客户区坐标转屏幕坐标:({x}, {y}) -> ({x_screen}, {y_screen})")
# 映射鼠标操作
operations = {
1: lambda: pyautogui.click(x_screen, y_screen),
2: lambda: pyautogui.doubleClick(x_screen, y_screen),
3: lambda: pyautogui.mouseDown(x=x_screen, y=y_screen, button='left'),
4: lambda: pyautogui.mouseUp(x=x_screen, y=y_screen, button='left')
}
# 获取对应的鼠标操作
operation = operations.get(action)
if not operation:
print(f"无效的鼠标操作: {action}")
return False
# 执行对应的鼠标操作
operation()
print(f"执行了鼠标操作: {action} 在 ({x_screen}, {y_screen})")
except Exception as e:
print("无法执行鼠标操作,出现异常:", e)
return False
finally:
# 恢复鼠标位置
pyautogui.moveTo(*original_pos)
return True |