0%

Windows下用Python模拟鼠标点击

由于某些需求,本人被安排了一个实现模拟按键的功能,虽然听说似乎按键精灵也有类似实现,但我的需求可能它无法满足,值得自己写。

对于Windows下的模拟,python一般是采用win32api,此外C++等也可以实现类似的功能,但是python简洁很多,适合不太熟悉Windows变成的人。

其实一开始是找到一个别人写的项目想直接用的,可惜运行失败,而且有部分需求不满足,有兴趣的可以直接试试PyUserInput

鼠标模拟

这一块基本和PyUserInput一样,因为我的需求没有那么复杂,所以只用了部分,有兴趣的可以看源码PyUserInput/pymouse

鼠标的基本操作可以分为:press(按下),release(释放),scroll(滚动,这里没写),move(移动)
在基本操作的基础上又有:click(按下+释放),drag(按下+移动+释放)

Press 按下

模拟在屏幕(x, y)的位置下按下鼠标,button=1是左键,button=2是右键

注意这里只模拟了点击操作,并没有修改鼠标的位置

1
2
3
4
5
import win32api

def press(x, y, button=1):
buttonAction = 2 ** ((2 * button) - 1)
win32api.mouse_event(buttonAction, x, y)

Release 释放

操作同上

1
2
3
4
5
import win32api

def release(x, y, button=1):
buttonAction = 2 ** ((2 * button))
win32api.mouse_event(buttonAction, x, y)

Move 移动

这里其实只是将鼠标设定到(x, y)的位置,并没有动画过程(写这个代码想想也没需要吧)

采用了ctypes这个库

1
2
3
4
import ctypes

def move(x, y):
ctypes.windll.user32.SetCursorPos(x, y)

Click 点击

点击 = 按下 + 释放

1
2
3
def click(x, y, button=1):
press(x, y, button)
release(x, y, button)

Drag 拖动

拖动 = 位置1按下 + 位置2释放

1
2
3
def drag(x1, y1, x2, y2):
self.press(x1, y1)
self.release(x2, y2)

获取当前鼠标位置

这里其实困扰了我一下,虽然ctypes中有函数可以实现这个功能,但传入的参数有点奇怪,应该是传入的一个指定类型的实例,并且直接将坐标点返回给这个实例。

1
2
3
4
5
6
7
8
9
10
import ctypes

class Point(ctypes.Structure):
_fields_ = [("x", ctypes.c_ulong),
("y", ctypes.c_ulong)]

def get_pos():
point = Point()
ctypes.windll.user32.GetCursorPos(ctypes.byref(point))
return point.x, point.y

参考资料