get barcode reader value form background monitoring

The barcode device behaves like a keyboard. When you have focus in a textbox, it sends characters to the textbox as if you typed them from the keyboard.

If you dont want to use a textbox, you’ll need to subscribe to a keyboard event handler to capture the barcode stream.

Form1.InitializeComponent():

this.KeyPress += new System.Windows.Forms.KeyPressEventHandler(this.Form1_KeyPress);

Handler & supporting items:

DateTime _lastKeystroke = new DateTime(0);
List<char> _barcode = new List<char>(10);

private void Form1_KeyPress(object sender, KeyPressEventArgs e)
{
    // check timing (keystrokes within 100 ms)
    TimeSpan elapsed = (DateTime.Now - _lastKeystroke);
    if (elapsed.TotalMilliseconds > 100)
        _barcode.Clear();

    // record keystroke & timestamp
    _barcode.Add(e.KeyChar);
    _lastKeystroke = DateTime.Now;

    // process barcode
    if (e.KeyChar == 13 && _barcode.Count > 0) {
        string msg = new String(_barcode.ToArray());
        MessageBox.Show(msg);
        _barcode.Clear();
    }
}

You’ll have to do keep track of the “keystrokes” and look out for the “carriage return” that is sent w/ the barcode stream. That can easily be done in an array. To differentiate between user keystrokes and barcode keystrokes, one dirty trick you can do is keep track of the timing of the keystrokes.

For example, if you get a stream of keystrokes less than 100ms apart ending w/ a carriage return, you can assume it is a barcode and process accordingly.

Alternatively, if your barcode scanner is programmable, you can also send special characters or sequences.

Leave a Comment