https://github.com/kennyhml/pyinterception?tab=readme-ov-file
https://github.com/oblitum/Interception/tree/v1.0.1
先装driver、setup,然后import。
打开:
https://github.com/oblitum/Interception/releases 找到 ,下载zip进行安装拦截环境。
然后
pip install setuptools wheel
pip install . 即可装入本地
键鼠库
监听键盘、鼠标
from interception import Interception, is_mouse, is_keyboard, FilterKeyFlag, FilterMouseButtonFlag, MouseStroke, \
KeyStroke
from interception.inputs import _get_keycode
def log_event(event):
"""打印事件日志"""
print(f"Received event: {event}")
def capture_events():
"""捕获鼠标和键盘事件并打印日志,同时确保操作不受干扰"""
context = Interception() # 创建 Interception 实例
# 设置过滤器以捕获鼠标左键和右键按下事件
context.set_filter(is_mouse,
FilterMouseButtonFlag.FILTER_MOUSE_LEFT_BUTTON_DOWN | FilterMouseButtonFlag.FILTER_MOUSE_RIGHT_BUTTON_DOWN)
context.set_filter(is_keyboard, FilterKeyFlag.FILTER_KEY_DOWN|FilterKeyFlag.FILTER_KEY_UP) # 也捕获键盘事件,避免干扰
print("Capturing events. Press ESC to stop.")
try:
while True:
device = context.await_input() # 等待输入
if device is None:
continue
stroke = context.devices[device].receive() # 接收输入
if stroke is None:
continue
# 记录事件
if isinstance(stroke, MouseStroke):
log_event(f"Mouse event: {stroke}")
# 重新发送捕获到的鼠标事件,以确保它们被传递给系统
context.send(device, stroke)
elif isinstance(stroke, KeyStroke):
log_event(f"Keyboard event: {stroke}")
# 重新发送捕获到的键盘事件,以确保它们被传递给系统
context.send(device, stroke)
# 如果检测到 ESC 键事件,则退出循环
if isinstance(stroke, KeyStroke) and stroke.code == _get_keycode("esc"):
break
finally:
context.destroy()
if __name__ == "__main__":
capture_events()
开关案例
from interception import Interception, is_mouse, is_keyboard, FilterKeyFlag, FilterMouseButtonFlag, MouseStroke, \
KeyStroke
from interception.inputs import _get_keycode
def log_event(event):
"""打印事件日志"""
print(f"Received event: {event}")
def capture_events():
"""捕获鼠标和键盘事件并打印日志,同时确保操作不受干扰"""
context = Interception() # 创建 Interception 实例
# 设置过滤器以捕获鼠标和键盘事件
context.set_filter(is_mouse, FilterMouseButtonFlag.FILTER_MOUSE_LEFT_BUTTON_DOWN)
context.set_filter(is_keyboard, FilterKeyFlag.FILTER_KEY_DOWN)
print("Capturing events. ")
is_paused = False
try:
while True:
device = context.await_input() # 等待输入
if device is None:
continue
stroke = context.devices[device].receive() # 接收输入
if stroke is None:
continue
if isinstance(stroke, KeyStroke):
# 检测到 '-' 键,切换监控状
if stroke.code == 12:
is_paused = not is_paused
if is_paused:
print("Paused. Press - to resume.")
else:
print("Resumed. Press - to pause.")
continue
# 检测到 0 键,退出程序
if stroke.code == _get_keycode("0"):
break
# 记录事件
if isinstance(stroke, MouseStroke):
# log_event(f"Mouse event: {stroke}")
# 重新发送捕获到的鼠标事件,以确保它们被传递给系统
context.send(device, stroke)
# 在监听状态下按下 '打印'
if not is_paused:
# interception.press("a")
print("元神,启动!!")
elif isinstance(stroke, KeyStroke):
# log_event(f"Keyboard event: {stroke}")
# 重新发送捕获到的键盘事件,以确保它们被传递给系统
context.send(device, stroke)
finally:
context.destroy()
if __name__ == "__main__":
capture_events()