2013-05-17 12 views
3

마찬가지로 Ctl, Alt + deleteWindows에서 3 개의 인수로 글로벌 단축키를 만드는 방법은 무엇입니까?

python에서 3 개 이상의 인수가있는 전역 단축키를 사용하는 프로그램을 작성하고 싶습니다. 키보드의 세 키를 모두 눌러야 할당 된 기능을 수행 할 수 있습니다. 예를 들어 고도, 창 및 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)") 

Registering 3 hotkeys? Possible? 하나 하나의 키를 할당 사용할 수있는 방법을 설명하는 그 중 두 개를 눌러야 할 경우. 그러나 나는 모든 기능이 동시에 눌려지면 기능 만 수행한다는 것을 알지 못한다. 내가 걸렸습니다

+0

https://github.com/boppreh/keyboard – Andrew

답변

4

alt, windows 및 F3을 원할 경우 HOTKEYS 항목에 win32con.VK_F3, win32con.MOD_ALT, win32con.MOD_WIN을 사용할 필요가 없습니까?

하지만, 정말 이해가 승리F5 키의 수정과를 눌러 F3 말을하지 않습니다. 광고에

오류 각 사전 엔트리의 값이 가변 길이 tuple 때문에

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

이다. 다음은 비트 단위로 또는을 모두 처리하여 하나의 인수로 RegisterHotKey()에 전달하기위한 준비에서 모든 수정 자 값을 처리하는 방법입니다. 코드가 제대로 들여 쓰기이고 PEP 8 -- Style Guide for Python Code 권고를 따른다면

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) 

당신의 문제에 일을 더 쉬웠을 것이다. 앞으로도 그렇게 생각하십시오.

4

이 주제와 관련하여 세부 사항과보다 정교한 예제 인에 관심이있는 사용자를 위해 최근에 win32con에서 제공하는 단축키 기능을 시연하는 짧은 프로그램을 작성했습니다. 이 프로그램 있습니다 UP

# 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) 

> 테스트 단축키 ALT + 화살표 -python.exe hotkey.py MOD_ALT VK_UP :

사용법 :이 프로그램은 사용자가 지정하고 명령 줄을 통해 원하는 단축키를 테스트 할 수 있습니다 프로그램의 일부로 (예 : 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 
+0

수 있도록 제안 이것은 [Active State Python Recipe] (http://code.activestate.com/recipes/langs/python/)이며 여기에 막연한 관련 질문에 대한 답변이 아닌 코멘트에 링크를 게시 할 수 있습니다 이 웹 사이트에 – martineau