1

I was trying to capture Shift+PrintScreen as Ctrl+c was captured in this answer.

Although the answer is outdated, but even if I fix the import, it doesn't works:

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

I wanted to capture PrintScreen key and open my Screenshot application, which I was able to do. Now I want to capture Shift + PrintScreen and open my application with some other config. How can I capture both key at once?

Max
  • 87
  • 11
Santosh Kumar
  • 26,475
  • 20
  • 67
  • 118

1 Answers1

4

pyhook source code::HookManager.py lists all defined key constants. In your case you'll have to check for the Keystate VK_LSHIFT in combination with the event.KeyID VK_SNAPSHOT (PrintScrn Key). Here's a working example:

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

If you want to also bind it to the right-shift-key you'll have to check for the VK_RSHIFT keystate.

if (GetKeyState(HookConstants.VKeyToID('VK_LSHIFT')) or GetKeyState(HookConstants.VKeyToID('VK_RSHIFT'))) and event.KeyID == HookConstants.VKeyToID('VK_SNAPSHOT'):
tintin
  • 3,176
  • 31
  • 34
  • Well I got Shift+PrintScreen working, I can't capture Ctrl+D. – Santosh Kumar Nov 19 '15 at 20:22
  • @SantoshKumar I've updated the code to properly capture ctrl+d. – tintin Nov 19 '15 at 22:04
  • Thanks a lot for the help @tintin. There no active development in this pyHook field so finding answers are so painful. Thanks for the help. Take extra 50 reputation as a gift. ;) How can I connect with you? – Santosh Kumar Nov 21 '15 at 04:30
  • you're welcome. I'll be around, feel free to ask questions or ping me if you feel like your're hitting a dead end. – tintin Nov 21 '15 at 12:37