4

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.

Ecno92
  • 869
  • 11
  • 16

1 Answers1

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()
unbehagen
  • 113
  • 5
  • The problem with this approach is that the scanner will send the barcode to both the keylogger and the application with focus. – Mark Ransom Feb 07 '13 at 15:23
  • If the scanner is really configured to act as a keyboard, there is probably no good way to prevent this. – unbehagen Feb 07 '13 at 16:29
  • Thanks for the answer. Unfortunately there seems to be no solution to hook a specific keyboard emulated device. This solution is fine and ensures that every time I want to scan i get the input into the program (and the program in front), but I think I have to search for another scanner with a different input type (raw data) in order to make it also work silently. Or are there any methods available to capture a specific keyboard? – Ecno92 Feb 15 '13 at 12:31
  • The equivalent of pyhook in linux is evdev, which allows python to 'grab' exclusive access to the HID device for scanner. – gatorback Nov 08 '16 at 05:13