C
C
Canckt2014-07-17 23:48:33
Python
Canckt, 2014-07-17 23:48:33

How to track keystrokes in Python with pyHook if the program window is not in focus?

Actually, the main goal is to control the Python program hanging in the tray using the keys on the keyboard. Peeped the tracking method here - Python: how to catch keyboard shortcuts? I edited the code for myself:
import win32api
import win32con
import pythoncom
import pyHook
def OnKeyboardEvent(event):
if event.Key=='F4' and event.MessageName == 'key down':
print ("The key was pressed")
x, y = win32api.GetCursorPos()
print (x,y)
return True
hm = pyHook.HookManager()
hm.KeyAll = OnKeyboardEvent
hm.HookKeyboard()
pythoncom.PumpMessages()
As a result, if the window with IDLE is in focus, everything works like clockwork. Otherwise, when pressing the desired key (F4), an error pops up:
TypeError: KeyboardSwitch() missing 8 required positional arguments: 'msg', 'vk_code', 'scan_code', 'ascii', 'flags', 'time', 'hwnd ', and 'win_name' Tell me
how to fix it?

Answer the question

In order to leave comments, you need to log in

2 answer(s)
C
Canckt, 2014-07-18
@Canckt

Is it possible to somehow implement the control of a program hanging in the tray using the keys? For ALL clicks to be detected

T
TomasHuk, 2014-07-18
@TomasHuk

Unfortunately, there is such a problem. As I understand it, if there are Cyrillic characters in the window name, then it gives this error. Found a fork of pyHook pyhook_py3k , which says the following:


Fixed unicode decoding bug of window title. This bug may cause crashing on exit randomly. Usually with console output:
TypeError: MouseSwitch() takes exactly 9 arguments (1 given)
or
TypeError: KeyboardSwitch() takes exactly 9 arguments (1 given)

I don’t know how it was fixed in that fork, because the HookManager.py file still has the KeyboardSwitch(self, msg, vk_code, scan_code, asci... ) function , which gives this error.
So far I have not been able to run without an error, but maybe you need to think more.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question