使用pyhook3/pynput实现键盘连发

安装

pyhook在窗口标题为中文时会报错,必须安装pyhook3。

pip install pyhook3

可能存在以下问题:

  1. swig.exe不存在:
    http://www.swig.org/download.html
    下载解压,并将目录添加到环境变量中
  2. 提示缺少VC++ 14.0:
    Visual C++ Build Tools 2015
    下载安装,按默认值即可
  3. cl.exe不存在
    打开 C:\Program Files (x86)\Microsoft Visual C++ Build Tools\Visual C++ 2015 x86 x64 Cross Build Tools Command Prompt.lnk 然后在其中运行pip安装命令

监听键盘

使用pynput监听:

from pynput.keyboard import Key, Listener, Controller
import time
from threading import Lock, Thread
import random

lock = Lock()
abilities = set()
hot_keys = {
    Key.f1: 'q',
    Key.f2: 'w',
    Key.f3: 'e',
    Key.f4: 'r'
}
keyboard = Controller()


def cast_ability():
    while True:
        time.sleep(0.001)
        bak = list(abilities)
        random.shuffle(bak)
        for ability in bak:
            time.sleep(random.uniform(0.05, 0.1))
            keyboard.press(ability)
            keyboard.release(ability)


def toggle_ability_status(key):
    if key in hot_keys:
        ability = hot_keys[key]
        with lock:
            if ability in abilities:
                abilities.remove(ability)
            else:
                abilities.add(ability)


threads = [Thread(target=cast_ability), Listener(on_press=toggle_ability_status)]
for listener in threads:
    listener.start()
for listener in threads:
    listener.join()

使用PyHook3监听

import pythoncom
import PyHook3
from pynput.keyboard import Controller
import time
from threading import Lock, Thread
import random

lock = Lock()
abilities = set()
hot_keys = {
    'F1': 'q',
    'F2': 'w',
    'F3': 'e',
    'F4': 'r'
}
keyboard = Controller()


def cast_ability():
    while True:
        time.sleep(0.001)
        bak = list(abilities)
        random.shuffle(bak)
        for ability in bak:
            time.sleep(random.uniform(0.05, 0.1))
            keyboard.press(ability)
            keyboard.release(ability)


def toggle_ability_status(event):
    key = event.Key
    if key in hot_keys:
        print(key)
        ability = hot_keys[key]
        with lock:
            if ability in abilities:
                abilities.remove(ability)
            else:
                abilities.add(ability)
    return True


hm = PyHook3.HookManager()
hm.KeyDown = toggle_ability_status
hm.HookKeyboard()
Thread(target=cast_ability).start()
pythoncom.PumpMessages()

你可能感兴趣的:(python)