Read barcode when program doesn't have focus?
I’d like to write a simple program that reads a 开发者_运维技巧barcode, and makes a note of the barcode as well as the time it was scanned in. Unfortunately I cannot guarantee that the program will have focus when the code is scanned. My understanding is that most barcode scanners act like a keyboard so if the program does not have focus I will have issues. What are the ways to deal with this? Note I’d prefer to code this in Java but I can use .net if the libraries make it easier. I also don’t have a specific scanner in mind so if one model will work better for this that info would be appreciated. I’ve sceen this question but it assumes the app has focus.
Most barcode scanners behave like a keyboard, hence requiring the processing application to have input focus. There are however also barcode scanners, which connect to the serial port or are connected to the USB and offer a virtual serial port interface.
These scanners must be accessed through the real or virtual serial port. For Java, you will need to use the Java Communications API or any other 3rd party library offering access to the serial ports, since this is not possible with the standard Java API.
Most keyboard wedge barcode scanners can be configured (via configuration barcodes) to emulate a keypress of a function key before sending the barcode data. The Windows API includes a RegisterHotkey function to define system-wide hotkeys. When the hotkey is pressed, you could give focus to your program's window to read the barcode.
A Google search reveals a library to register system-wide hotkeys from Java. There's also a question on this site about it, which seems to suggest that there isn't a publicly available library to do so in Mac OS X, though one of the answerers posted a link to such a library he was developing.
After some research on this I implemented as jarnbjo mentioned with a virtual serial port, an example is here (see my answer).
精彩评论