问题
I'm struggling with an issue for some days and I can't get it working. I've just started with python and I'm now already facing the biggest problem which I will face in this project.
Here's the situation: I have to make a program which scans a barcode. Communicates this to a online service and prints a PDF. This all works fine, but I also want to scan the barcode when the window is "out of focus". So I want to allow people to scan with the barcode scanner while they have the window minimized.
I'm running windows 8 and I'm working with python 3.3. The barcode scanner is a HID device and it presents itself as a keyboard. I already tried to convert this project to python 3.3, but it does not work. --> http://learn.adafruit.com/barcode-scanner/overview I end up with all kinds of errors, which I still not completly understand.
Today I tried to use pywinusb, but this module seems to have issues regarding to finding any HID device because it also can't find my keyboard and mouse.
Maybe it's a complicated question, but hopefully someone has expirience with this and knows how to get this working.
回答1:
If the barcode scanner presents itself as a keyboard, isn't what you want basically a key logger that runs in the background?
Searching for it, this was among the first google results for "python keylogger" - according to the source, it needs pyWin32 and pyHook. I removed the logging to reduce the code sample to a minimum, just put the handling code inOnKeyboardEvent
. I tested this and it works with my Python 2.7 installation on Windows 7, but the modules should be compatible with Python 3.3.
import pythoncom, pyHook, sys, logging
def OnKeyboardEvent(event):
print "Key: ", chr(event.Ascii)
logging.log(10,chr(event.Ascii))
return True
hm = pyHook.HookManager()
hm.KeyDown = OnKeyboardEvent
hm.HookKeyboard()
pythoncom.PumpMessages()
来源:https://stackoverflow.com/questions/14749458/read-hid-input-while-window-is-out-of-focus-in-python