如何使用 pyHook 捕获 Shift + PrintScreen?

How to capture Shift + PrintScreen with pyHook?

我试图将 Shift+PrintScreen 捕获为 Ctrl+cthis answer.

中被捕获

虽然答案已经过时,但即使我修复了导入,它也不起作用:

import pythoncom
from pyHook import HookManager, GetKeyState, HookConstants

def OnKeyboardEvent(event):
    ctrl_pressed = GetKeyState(HookConstants.VKeyToID('VK_CONTROL') >> 15)
    if ctrl_pressed and HookConstant.IDToName(event.keyId) == 'd':
        print("ctrl plus d was pressed at same time")

    return True

# create a hook manager
hm = HookManager()
# watch for all keyboard events
hm.KeyDown = OnKeyboardEvent
# set the hook
hm.HookKeyboard()
# wait forever
pythoncom.PumpMessages()

我想捕获 PrintScreen 键并打开我的屏幕截图应用程序,我能够做到。现在我想捕获 Shift + PrintScreen 并使用其他一些配置打开我的应用程序。如何同时捕获两个密钥?

pyhook source code::HookManager.py 列出所有已定义的键常量。在您的情况下,您必须检查 Keystate VK_LSHIFTevent.KeyID VK_SNAPSHOT (PrintScrn 键)。这是一个工作示例:

import pythoncom
from pyHook import HookManager, GetKeyState, HookConstants

def OnKeyboardEvent(event):
    # in case you want to debug: uncomment next line
    # print repr(event), event.KeyID, HookConstants.IDToName(event.KeyID), event.ScanCode , event.Ascii, event.flags
    if GetKeyState(HookConstants.VKeyToID('VK_LSHIFT')) and event.KeyID == HookConstants.VKeyToID('VK_SNAPSHOT'):
        print("shift + snapshot pressed")
    elif GetKeyState(HookConstants.VKeyToID('VK_CONTROL')) and HookConstants.IDToName(event.KeyID) == 'D':
        print("ctrl + d pressed")
    return True

# create a hook manager
hm = HookManager()
# watch for all mouse events
hm.KeyDown = OnKeyboardEvent
# set the hook
hm.HookKeyboard()
# wait forever
pythoncom.PumpMessages()

如果您还想将其绑定到右移键,则必须检查 VK_RSHIFT 键状态。

if (GetKeyState(HookConstants.VKeyToID('VK_LSHIFT')) or GetKeyState(HookConstants.VKeyToID('VK_RSHIFT'))) and event.KeyID == HookConstants.VKeyToID('VK_SNAPSHOT'):