Search code examples
c#barcode

C# + USB Barcode Reader


How can i read barcode text in background in my C# app? I googled but its of no use. And other resources on stackoverflow are not close to what i need. I want to read barcode in background. And i want to know if the data is coming from barcode or key board. If the data comes from the barcode then it mustnot be displayed on textbox even though the textbox is highlighted. I got similar code for stackoverflow but if there is presence of textbox in the window then the textbox will contain barcode data; which i dont want. Link : get barcode reader value form background monitoring

    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();
        }
    }

Solution

  • Most barcode scanners simply act as keyboard inputs and a quick / easy work around is to place a textbox "Out of sight". An example would be something like this:

    // Pseudo code (could be Web, Windows etc)
    public void Form1_Load()
    {
        txtBarcodeScanner.Top = -10000;
        txtBarcodeScanner.Left = -10000;
        txtBarcodeScanner.Width = 10;
        txtBarcodeScanner.Height = 10;
        txtBarcodeScanner.Focus();
    }
    

    That way the input can be captured by txtBarcodeScanner but will not be visible and the barcode will not seen being captured but will fire KeyDown etc.