Get keystrokes during background execution in Python (windows)

Introduction

It may not be in great demand, but there are rare times when you want to get keystrokes while running in the background (that is, the Python app is out of focus). Java has a library called JNativeHook, which is reasonably easy to use, but I think that Java is used just for that. As a result of searching for a way to do it with Python, I got stuck, so I will leave a memorandum.

environment

Although there is something called PyHook. .. ..

The first thing I looked up and found in various places was how to use PyHook. It seems that you can move in the background and take events such as key down and key up (Interesting miscellaneous feelings-moss about pyHook).

I dropped the corresponding version of pyHook from http://www.lfd.uci.edu/~gohlke/pythonlibs to give it a try.

wheel install pyHook‑1.5.1‑cp36‑cp36m‑win_amd64.whl

Installed with (it took a lot of time due to version problems etc.).

from pyHook import HookManager
from win32gui import PumpMessages, PostQuitMessage

class Keystroke_Watcher(object):
    def __init__(self):
        self.hm = HookManager()
        self.hm.KeyDown = self.on_keyboard_event
        self.hm.HookKeyboard()


   def on_keyboard_event(self, event):
        try:
            print ('MessageName:',event.MessageName)
            print ('Ascii:', repr(event.Ascii), repr(chr(event.Ascii)))
            print ('Key:', repr(event.Key))
            print ('KeyID:', repr(event.KeyID))
            print ('ScanCode:', repr(event.ScanCode))
            print ('Time:',event.Time)
            print ('-'*5)
        finally:
            return True

   def your_method(self):
        pass

   def shutdown(self):
        PostQuitMessage(0)
        self.hm.UnhookKeyboard()


watcher = Keystroke_Watcher()
PumpMessages()

I tried to execute, but it works fine when using Emacs, Sublime Text, but in a mysterious situation that it falls when I hit a key on the chrome browser. As an error

TypeError: KeyboardSwitch() missing 8 required positional arguments: 'msg', 'vk_code', 'scan_code', 'ascii', 'flags', 'time', 'hwnd', and 'win_name'

As a result of investigating, it seems to be a bug that occurs when executed on Python 3 system (https://stackoverflow.com/questions/26156633/pythoncom-crashes-on-keydown-when-used-hooked -to-certain-applications), I'm sorry.

PyHooked

When I was looking for a good alternative, I found something called pyHooked. Installation is

pip install pyhooked

And as you can see in example.py on the Github page,

from pyhooked import Hook, KeyboardEvent, MouseEvent


def handle_events(args):
    if isinstance(args, KeyboardEvent):
        print(args.key_code, args.current_key, args.event_type)

    if isinstance(args, MouseEvent):
        print(args.mouse_x, args.mouse_y)

hk = Hook()  # make a new instance of PyHooked
hk.handler = handle_events  # add a new shortcut ctrl+a, or triggered on mouseover of (300,400)
hk.hook()  # hook into the events, and listen to the presses

By creating an event handler, you can easily take keyboard and mouse input in the background.

reference

--Interesting miscellaneous feelings- What was moss about pyHook (http://d.hatena.ne.jp/favcastle/20120206/1328537612) - LoG- msvcrt.kbhit () (http://jn1inl.blog77.fc2.com/blog-entry-2039.html)

Recommended Posts

Get keystrokes during background execution in Python (windows)
Get date in Python
Get YouTube Comments in Python
Get Terminal size in Python
Explicitly get EOF in python
External command execution in Python
Get Evernote notes in Python
Python install in 2 lines @Windows
Detect keystrokes in python (tty)
Get Japanese synonyms in Python
Get Leap Motion data in Python.
Hit a command in Python (Windows)
Put MeCab in "Windows 10; Python3.5 (64bit)"
Get data from Quandl in Python
Get the desktop path in Python
Get the script path in Python
Measure function execution time in Python
Windows10: Install MeCab library in python
Get, post communication memo in Python
Detect keystrokes in Python (without Enter)
Python unittest module execution in vs2017
Get the desktop path in Python
Get the host name in Python
Get started with Python in Blender
If you get stuck in Cannot load mkl_intel_thread.dll in Python on Windows
Get additional data in LDAP with python
Get exchange rates from open exchange rates in Python
Get Suica balance in Python (using libpafe)
Using venv in Windows + Docker environment [Python]
Debug step execution in Python (Bottle, Intellij)
[Python] [Windows] Serial communication in Python using DLL
Get Google Fit API data in Python
[Python] [Windows] Take a screen capture in Python
How to get a stacktrace in python
Get Youtube data in Python using Youtube Data API
Get battery level from SwitchBot in Python
Get a token for conoha in python
Get Started with TopCoder in Python (2020 Edition)
Get the EDINET code list in Python
Get Precipitation Probability from XML in Python
Get Cloud Logging available in Python in 10 minutes
Parallel task execution using concurrent.futures in Python
Python garbled in Windows + Git Bash environment
Get rid of DICOM images in Python
Get metric history from MLflow in Python
Get your own IP address in Python
[Python] Get the files in a folder with Python
Get the weather in Osaka via WebAPI (python)
Simply build a Python 3 execution environment on Windows
Get the caller of a function in Python
Get multiple maximum keys in Python dictionary type
Get image URL using Flickr API in Python
Install Python 3.5.1 + numpy + scipy + α in Windows environment
Get the X Window System window title in Python
Get pointers to struct members in Python ctypes
How to get the files in the [Python] folder
GUI (WxPython) executable file (pyInstaller) [Windows] in Python3
Get files, functions, line numbers running in python
Get a glimpse of machine learning in Python
What to do to get google spreadsheet in python
Get only articles from web pages in Python