-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathautoclicker.py
More file actions
118 lines (93 loc) · 3.79 KB
/
Copy pathautoclicker.py
File metadata and controls
118 lines (93 loc) · 3.79 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
"""
自动点击器 - 在桌面指定位置自动点击,每 200ms 一次。
停止条件(任意一个触发即立刻结束程序):
1. 检测到鼠标移动(人工移动鼠标)
2. 检测到人工鼠标点击 / 滚轮操作
3. 检测到键盘任意输入
用法:
python autoclicker.py # 倒计时结束后,在当前鼠标位置点击
python autoclicker.py 800 600 # 在屏幕坐标 (800, 600) 处点击
依赖: pip install pynput
"""
import sys
import time
import threading
from pynput import mouse, keyboard
# ---------- 全局状态 ----------
stop_event = threading.Event() # 任意停止条件触发即 set
clicking = threading.Event() # 标记「程序自己的点击/移动进行中」,用于忽略自身产生的事件
THRESHOLD = 5 # 鼠标漂移阈值(像素),超过视为人工移动
def trigger_stop(reason: str = ""):
"""触发停止(只打印一次原因)"""
if not stop_event.is_set():
print(f"\n[已触发停止] {reason}")
stop_event.set()
# ---------- 键盘监听: 任意按键按下即停 ----------
def on_key_press(key):
trigger_stop(f"检测到键盘输入: {key}")
return False # 停止键盘监听
# ---------- 鼠标监听 ----------
def on_move(x, y):
if clicking.is_set(): # 忽略程序自身把鼠标移到目标位置造成的移动
return
trigger_stop(f"检测到鼠标移动到 ({x}, {y})")
return False
def on_click(x, y, button, pressed):
if clicking.is_set(): # 忽略程序自身的点击
return
trigger_stop(f"检测到人工鼠标点击: {button} {'按下' if pressed else '松开'}")
return False
def on_scroll(x, y, dx, dy):
if clicking.is_set():
return
trigger_stop("检测到滚轮操作")
return False
def main():
# 解析目标坐标 (可选命令行参数)
if len(sys.argv) >= 3:
target = (int(sys.argv[1]), int(sys.argv[2]))
print(f"目标位置(命令行指定): {target}")
else:
target = None
ctrl = mouse.Controller()
# 3 秒倒计时: 方便把鼠标移到目标位置 / 切换到目标窗口
print("3 秒后开始自动点击 ……")
if target is None:
print(" (未指定坐标,倒计时结束时将以鼠标所在位置为目标)")
for i in range(3, 0, -1):
print(f" {i} ...", flush=True)
time.sleep(1)
if target is None:
target = ctrl.position
print(f"开始点击 {target},间隔 200ms。移动鼠标 / 点击 / 滚轮 / 按任意键 即停止。")
# 启动监听线程 (daemon, 主线程退出时自动结束)
kl = keyboard.Listener(on_press=on_key_press)
ml = mouse.Listener(on_move=on_move, on_click=on_click, on_scroll=on_scroll)
kl.daemon = True
ml.daemon = True
kl.start()
ml.start()
try:
while not stop_event.is_set():
# 标记自身操作,避免监听器把我们的移动/点击误判为人工操作
clicking.set()
try:
ctrl.position = target # 先移到目标位置(保证点对地方)
ctrl.click(mouse.Button.left) # 左键点击一次
finally:
clicking.clear()
# 用 wait 替代 sleep: 停止信号一旦触发立刻返回,做到「立刻结束」
if stop_event.wait(0.2):
break
# 兜底: 若鼠标被人挪离目标(超出阈值)也停止
cx, cy = ctrl.position
if abs(cx - target[0]) > THRESHOLD or abs(cy - target[1]) > THRESHOLD:
trigger_stop(f"鼠标已偏离目标: ({cx}, {cy})")
except KeyboardInterrupt:
trigger_stop("Ctrl+C 中断")
finally:
kl.stop()
ml.stop()
print("程序已结束。")
if __name__ == "__main__":
main()