I have my barcode reader programmed to add a prefix and suffix of “,” and otherwise to work just like a keyboard. I have a Windows Form that will be open when barcodes are scanned.
Rather than writing a bunch of KeyDown code, Reactive Extensions seems perfect for this kind of work. What I’d like to do:
- When a comma is pressed, start holding on to key presses (don’t let them be handled by any control on the screen)
- Collect all keys until another comma is pressed or 250ms have gone by.
- If no comma is pressed within 250ms, hand the key presses back to whatever control is active.
- If comma is pressed, do processing on the string value scanned in from the barcode.
How can I use System.Reactive to hold key presses when matching a prefix and suffix for a barcode scanner, process if suffix is matched, but handle key presses normally when the suffix isn’t matched within a time limit?
Someone will come along and probably give a more elegant answer than this. But I found this one challenging.
First things first, this example does not show how to do it for keys on forms. There is sufficient additional complexity there that it bears trying yourself first, or asking another question. It would require a full application to answer all aspects of your question here. Suffice to say that:
KeyEventArgsthat make it into the barcode stream with SuppressKeyPressKeyEventArgsin the non-barcode streamThe solution as it stands involves defining a function that takes an
IObservable<char>and turns it into aGroupedObservablethat marks (with abool) whether the underlying char was inside a ‘barcode’ stream (true) or not (false):What this function is doing is:
And then a full usage example:
If you use
keys1, the key presses are too slow to find the first barcode, but it finds the second. If you usekeys2, the key presses are fast enough to find both barcodes.In either case, the
othersstream contains all keys that were not eventually marked as containing barcodes. Thebarcodesstream can be taken as a character by character stream, or converted into aListwith each set of barcodes as I did above.