from pynput import keyboard
hotkey_strings = ["<ctrl>+a","<ctrl>+<alt>+a","<ctrl>+<shift>+a","<ctrl>+<shift>+<alt>+a","<ctrl>+<cmd>+a","<alt>+a","<shift>+a","<cmd>+a","<ctrl>+~","<ctrl>+<f1>", "<ctrl>+1","<ctrl>+-","<ctrl>+=","<ctrl>+<backspace>","<ctrl>+<tab>","<ctrl>+q","<ctrl>+{","<ctrl>+}","<ctrl>+<enter>","<ctrl>+<caps_lock>","<ctrl>+;","<ctrl>+'",r"<ctrl>+\ ".strip(),"<ctrl>+|","<ctrl>+<shift_l>","<ctrl>+,","<ctrl>+.","<ctrl>+/","<ctrl>+<shift_r>","<ctrl>+<cmd_l>","<ctrl>+<alt_l>","<ctrl>+<space>","<ctrl>+<alt_r>","<ctrl>+<cmd_r>","<ctrl>+<menu>","<ctrl_l>+<ctrl_r>","<ctrl>+<insert>","<ctrl>+<delete>","<ctrl>+<home>","<ctrl>+<end>","<ctrl>+<page_up>","<ctrl>+<page_down>","<ctrl>+<up>","<ctrl>+<down>","<ctrl>+<left>","<ctrl>+<right>","<ctrl>+<print_screen>","<ctrl>+<scroll_lock>","<ctrl>+<pause>","<ctrl>+<num_lock>","<ctrl>+<96>", "<ctrl>+<105>", "<ctrl>+<106>", "<ctrl>+<107>", "<ctrl>+<109>", "<ctrl>+<110>", "<ctrl>+<111>",
]
def generate_random_hotkey():import randomrandom_hotkey_str = random.choice(hotkey_strings)if '+' in random_hotkey_str:parts = random_hotkey_str.split('+')for i, part in enumerate(parts):if len(part) == 1 and part.isalpha():random_char = chr(random.randint(ord('a'), ord('z')))parts[i] = random_charelif part.startswith('<f') and part.endswith('>'):random_f_key = f"<f{random.randint(1, 12)}>"parts[i] = random_f_keyrandom_hotkey_str = '+'.join(parts)try:parsed_hotkey = keyboard.HotKey.parse(random_hotkey_str)print(f"生成的快捷键为: {random_hotkey_str}")return parsed_hotkey, random_hotkey_strexcept ValueError as e:print(f"解析 '{random_hotkey_str}' 失败: {e}")return None, random_hotkey_str
def parse_hotkey_strings():for hotkey_str in hotkey_strings:try:parsed_hotkey = keyboard.HotKey.parse(hotkey_str)print(f"\033[1;32m解析 '{hotkey_str}' 结果为: {parsed_hotkey}\033[0m")except ValueError as e:print(f"\033[1;31m解析 '{hotkey_str}' 失败: {e}\033[0m")
def test_numpad_hotkey():hotkey_s = '<ctrl>+<105>'def on_activate():print(f"按下了{hotkey_s}")def for_canonical(f):return lambda k: (setattr(k, '_scan', None), f(listener.canonical(k)))hotkey = keyboard.HotKey(keyboard.HotKey.parse(hotkey_s), on_activate)listener = keyboard.Listener(on_press=for_canonical(hotkey.press), on_release=for_canonical(hotkey.release))listener.start()import time;time.sleep(5)listener.stop()listener.join()
def print_vk_on_press():def format_key_info(key):key_info = f" {key}"if hasattr(key, 'char'):key_info += f' char:{key.char}'if hasattr(key, 'vk'):key_info += f' vk:{key.vk}'return key_infodef on_press(key):print(format_key_info(key))def on_release(key):print('{0} released'.format(key))if key == keyboard.Key.esc:import os;os._exit(0) listener = keyboard.Listener(on_press=on_press, on_release=on_release)listener.start()import timetime.sleep(10)listener.stop()listener.join()if __name__ == "__main__":passfor i in range(10):generate_random_hotkey()
随机

测试

小键盘

vk码
