I'd like a Python script to run constantly in background and do something when a certain keyboard shortcut is pressed, such as WIN+A.
I've read Key Listeners in python? and solutions using pynput
, but it seems to work and detect key presses when the window/console has focus.
Question: how to detect a keyboard shortcut in Python, such as WIN+A, and launch a function when it happens, even if the focus is somewhere else (e.g. browser, etc.)?
Note: my OS is Windows. Also I would prefer that the Python script only "registers" listening to WIN+A (does this exist?), and does not listen to all keypresses (otherwise it would be more or less a keylogger, which I don't want!).
Here is what I have tried:
import pyHook, pythoncom
def OnKeyboardEvent(event):
if event.Ascii == 8: # backspace
print('hello')
return True
hm = pyHook.HookManager()
hm.KeyDown = OnKeyboardEvent
hm.HookKeyboard()
pythoncom.PumpMessages()
I would like to avoid it for 2 reasons: first, I find it very intrusive to listen to all keypresses and secondly, this common example about pyhook
I found in many places has a bug: TypeError: KeyboardSwitch() missing 8 required positional arguments: 'msg', 'vk_ code', 'scan_code', 'ascii', 'flags', 'time', 'hwnd', and 'win_name'
. The new version PyHook3 doesn't seem to work for Py36-64 either: pip install PyHook3
fails on Windows.