Python DirectX 鼠标模拟:使用 ctypes 库控制鼠标
以下是使用 DirectX 和 Python 调用模拟鼠标的示例代码:
import ctypes
import time
# 定义常量
MOUSEEVENTF_MOVE = 0x0001 # 移动鼠标
MOUSEEVENTF_LEFTDOWN = 0x0002 # 左键按下
MOUSEEVENTF_LEFTUP = 0x0004 # 左键释放
MOUSEEVENTF_RIGHTDOWN = 0x0008 # 右键按下
MOUSEEVENTF_RIGHTUP = 0x0010 # 右键释放
# 定义结构体
class MOUSEINPUT(ctypes.Structure):
_fields_ = (('dx', ctypes.c_long),
('dy', ctypes.c_long),
('mouseData', ctypes.c_ulong),
('dwFlags', ctypes.c_ulong),
('time', ctypes.c_ulong),
('dwExtraInfo', ctypes.POINTER(ctypes.c_ulong)))
# 定义函数
def move_mouse(x, y):
# 创建结构体实例
mouse_input = MOUSEINPUT()
mouse_input.dx = int(x * (65536 / ctypes.windll.user32.GetSystemMetrics(0)) + 1)
mouse_input.dy = int(y * (65536 / ctypes.windll.user32.GetSystemMetrics(1)) + 1)
mouse_input.mouseData = 0
mouse_input.dwFlags = MOUSEEVENTF_MOVE
mouse_input.time = 0
mouse_input.dwExtraInfo = None
# 调用鼠标事件
input_array = (MOUSEINPUT * 1)(mouse_input)
ctypes.windll.user32.SendInput(1, ctypes.pointer(input_array[0]), ctypes.sizeof(MOUSEINPUT))
def click_mouse(button):
down_flag = None
up_flag = None
if button == 'left':
down_flag = MOUSEEVENTF_LEFTDOWN
up_flag = MOUSEEVENTF_LEFTUP
elif button == 'right':
down_flag = MOUSEEVENTF_RIGHTDOWN
up_flag = MOUSEEVENTF_RIGHTUP
# 创建结构体实例
mouse_input = MOUSEINPUT()
mouse_input.dx = 0
mouse_input.dy = 0
mouse_input.mouseData = 0
mouse_input.dwFlags = down_flag
mouse_input.time = 0
mouse_input.dwExtraInfo = None
# 调用鼠标事件(按下)
input_array = (MOUSEINPUT * 1)(mouse_input)
ctypes.windll.user32.SendInput(1, ctypes.pointer(input_array[0]), ctypes.sizeof(MOUSEINPUT))
# 等待一段时间
time.sleep(0.1)
# 创建结构体实例
mouse_input.dwFlags = up_flag
# 调用鼠标事件(释放)
input_array = (MOUSEINPUT * 1)(mouse_input)
ctypes.windll.user32.SendInput(1, ctypes.pointer(input_array[0]), ctypes.sizeof(MOUSEINPUT))
# 示例代码
move_mouse(100, 100) # 移动鼠标到坐标(100, 100)
click_mouse('left') # 模拟左键点击
请确保你已经安装了ctypes库,并且在 Windows 操作系统上运行此代码。
原文地址: https://www.cveoy.top/t/topic/o7bH 著作权归作者所有。请勿转载和采集!