如何在Windows上创建一个全局热键有3个参数?(How to create a global h

2019-09-04 03:35发布

就像CTL,ALT + DELETE

我想编写一个程序,它使用与蟒蛇3个或多个参数全局热键。 当我按下键盘上的所有三个按键分配的功能只能执行。 例如ALT,窗户和F3。

win32con.VK_F3, win32con.MOD_WIN, win32con.VK_F5

这是当前节目我要运行,然而它的输出是:

Traceback (most recent call last):
 File "C:\Python32\Syntax\hot keys\hotkeys2.py", line 41, in <module>
   for id, (vk, modifiers) in HOTKEYS.items ():
ValueError: too many values to unpack (expected 2)

该程序:

import os
import sys
import ctypes
from ctypes import wintypes
import win32con

byref = ctypes.byref
user32 = ctypes.windll.user32

HOTKEYS = {
  1 : (win32con.VK_F3, win32con.MOD_WIN, win32con.VK_F5),
  2 : (win32con.VK_F4, win32con.MOD_WIN),
  3 : (win32con.VK_F2, win32con.MOD_WIN)
    }

    def handle_win_f3 ():
  #os.startfile (os.environ['TEMP'])
  print ("Hello WOrld! F3")

def handle_win_f4 ():
  #user32.PostQuitMessage (0)
    print ("Hello WOrld! F4")

def handle_win_f1_escape ():
    print("exit")
    sys.exit()

HOTKEY_ACTIONS = {
  1 : handle_win_f3,
  2 : handle_win_f4,
  3 : handle_win_f1_escape
}

for id, (vk, modifiers) in HOTKEYS.items ():
  print ("Registering id", id, "for key", vk)
  if not user32.RegisterHotKey (None, id, modifiers, vk):
    print ("Unable to register id", id)

try:
  msg = wintypes.MSG ()
  while user32.GetMessageA (byref (msg), None, 0, 0) != 0:
    if msg.message == win32con.WM_HOTKEY:
      action_to_take = HOTKEY_ACTIONS.get (msg.wParam)
      #print(" msg.message == win32con.WM_HOTKEY:")
      if action_to_take:
        action_to_take ()

    user32.TranslateMessage (byref (msg))
    user32.DispatchMessageA (byref (msg))

finally:
  for id in HOTKEYS.keys ():
    user32.UnregisterHotKey (None, id)
    print("user32.UnregisterHotKey (None, id)")

注册3个热键? 可能? 介绍一个如何使用分配需要按下一个键,然后,如果其中两个或者需要被按下。 但是我不会说的功能,只有当所有有同时按下执行。 我拿了

Answer 1:

对于初学者来说,如果你想ALT,窗户和F3,你会不会需要使用win32con.VK_F3, win32con.MOD_ALT, win32con.MOD_WINHOTKEYS进入?

然而,它并没有真正意义地说按F3胜利的改性剂 F5键。

上线的错误:

for id, (vk, modifiers) in HOTKEYS.items ():

是因为每个字典条目的值是可变长度tuple 。 这里是来处理这也位在准备一切都在修改值一起将它们作为单个参数的方式RegisterHotKey()

from functools import reduce

for id, values in HOTKEYS.items ():
    vk, modifiers = values[0], reduce (lambda x, y: x | y, values[1:])
    print ("Registering id", id, "for key", vk)
    if not user32.RegisterHotKey (None, id, modifiers, vk):
        print ("Unable to register id", id)

这本来是容易对你的问题的工作,如果你的代码是缩进正确,并遵循PEP 8 -风格指南Python代码的建议。 请考虑在将来这样做。



Answer 2:

对于细节有兴趣和更复杂的例子关于这个话题,我最近写了一个小程序演示由win32con提供的热键功能。 该计划允许您指定并测试你通过命令行想要的任何热键:

用法: python.exe hotkey.py MOD_ALT VK_UP - >测试热键ALT +箭头向上

# Imports
import win32con
import ctypes, ctypes.wintypes
import sys

#
# Functions
#
def dispatch_hotkey(msg):
    mod = msg.lParam & 0b1111111111111111
    key = msg.lParam >> 16
    bit = bin(msg.lParam)[2:]
    print("\n*** Received hotkey message (wParam: %d, lParam: %d)" % (msg.wParam, msg.lParam))
    print("lParam bitmap: %s" % bit)
    print("lParam low-word (modifier): %d, high-word (key): %d" % (mod, key))
    print("-> Hotkey %s with modifier %s detected\n" % (keys[key], mods[mod]))

#
# Main
#

# Build translation maps (virtual key codes / modifiers to string)
# Note: exec() is a hack and should not be used in real programs!!
print("\n*** Building translation maps")
mods = {}
keys = {}
for item in dir(win32con):
    if item.startswith("MOD_"):
        exec("mods[item] = win32con." + item)
        exec("mods[win32con." + item + "] = '" + item + "'")
    if item.startswith("VK_"):
        exec("keys[item] = win32con." + item)
        exec("keys[win32con." + item + "] = '" + item + "'")

# Process command line
print("\n*** Processing command line")

mod = "MOD_WIN"
key = "VK_ESCAPE"
for param in sys.argv:
    if param.startswith("MOD_"):
        if param in mods: mod = param
        else: print("\nInvalid modifier specified (%s). Using default.\n-> Use '--list-mods' for a list of valid modifiers." % param)
    if param.startswith("VK_"):
        if param in keys: key = param
        else: print("\nInvalid key specified (%s). Using default.\n-> Use '--list-keys' for a list of valid keys." % param)

if "--list-mods" in sys.argv:
    print("\nAvailable modifiers:")
    for item in dir(win32con):
        if item.startswith("MOD_"): sys.stdout.write(item + ", ")
    print("\b\b ")

if "--list-keys" in sys.argv:
    print("\nAvailable keys:")
    for item in dir(win32con):
        if item.startswith("VK_"): sys.stdout.write(item + ", ")
    print("\b\b ")

# Register hotkey
print("\n*** Registering global hotkey (modifier: %s, key: %s)" % (mod, key))
ctypes.windll.user32.RegisterHotKey(None, 1, mods[mod], keys[key])

# Wait for hotkey to be triggered
print("\n*** Waiting for hotkey message...")
try:
    msg = ctypes.wintypes.MSG()
    while ctypes.windll.user32.GetMessageA(ctypes.byref(msg), None, 0, 0) != 0:
        if msg.message == win32con.WM_HOTKEY:
            dispatch_hotkey(msg)
            break
        ctypes.windll.user32.TranslateMessage(ctypes.byref(msg))
        ctypes.windll.user32.DispatchMessageA(ctypes.byref(msg))

# Unregister hotkey
finally:
    ctypes.windll.user32.UnregisterHotKey(None, 1)

请注意,这个计划的目的是用于演示目的仅作为程序的一部分(如exec函数)不应在生产环境中使用。 还要注意的是这种方法,你将无法覆盖内置的热键像WIN + E等,将它们简单忽略,仍然执行内置功能(例如打开资源管理器)。

另一种方式 (@martineau提供)

以下是如何打造的平移图不使用exec()

print("\n*** Building translation maps")
mods = {}
keys = {}
for item, value in vars(win32con).items():
    if item.startswith("MOD_"):
        mods[item] = value
        mods[value] = item
    elif item.startswith("VK_"):
        keys[item] = value
        keys[value] = item


文章来源: How to create a global hotkey on Windows with 3 arguments?