问题
My barcode reader is a HID type and use the USB.
I can get the data when the text box is focus and do some business logic.
private void Form1_KeyUp(object sender, KeyEventArgs e)
{
if (e.KeyValue == (char)Keys.Return)
{
e.Handled = true;
int barcodeLength = textBox1.TextLength;
textBox1.Select(0, barcodeLength);
queryData(textBox1.Text);
}
}
After I google, I found this article and try to implement to my application. But the problem now, the value return with double character. If string is F1234, it will return FF11223344 and so on.
Here the code
DateTime _lastKeystroke = new DateTime(0);
List<char> _barcode = new List<char>(10);
public Form1()
{
InitializeComponent();
this.KeyPress += new System.Windows.Forms.KeyPressEventHandler(this.Form1_KeyPress);
}
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());
queryData(msg);
_barcode.Clear();
}
}
Need advice to solve my problem
回答1:
Just comment the below line
//this.KeyPress += new System.Windows.Forms.KeyPressEventHandler(this.Form1_KeyPress);
来源:https://stackoverflow.com/questions/17090401/get-data-from-barcode-reader-without-textbox