I have a barcode scanner which reads the string of the barcode and displays in the active text box. The issue I am having, is that I need that barcode to be used as soon as its scanned (no user "ok" button).
When I do the Text Changed e开发者_运维问答vent, it fires as soon as the first character of the barcode is entered into the text box. (i.e if the barcode is 123r54122, it fires with '1' in the text box).
There is no consistent end character to the barcode, or standard length. So how would I go about firing a method when the WHOLE string has been read in?
You can verify text length (I think it is constant for bar codes). E.g. subscribe to TextChange event and if text length = barCodeLength then raise Scanned event.
If bar code has variable length you can try something like this: 1) define
private Timer _timer;
private DateTime _lastBarCodeCharReadTime;
2) initialize timer
_timer = new Timer();
_timer.Interval = 1000;
_timer.Tick += new EventHandler(Timer_Tick);
3) add handler
private void Timer_Tick(object sender, EventArgs e)
{
const int timeout = 1500;
if ((DateTime.Now - _lastBarCodeCharReadTime).Milliseconds < timeout)
return;
_timer.Stop();
// raise Changed event with barcode = textBox1.Text
}
4) in TextChanged event handler add this
private void textBox1_TextChanged(object sender, EventArgs e)
{
_lastBarCodeCharReadTime = DateTime.Now;
if (!_timer.Enabled)
_timer.Start();
}
The barcode scanners I've worked with add a newline (return/enter) to the end of the barcode string. Set the textbox to accept return (AcceptReturn to true) and then do something like
private void textBox1_KeyPress(object sender, KeyPressEventArgs e)
{
if (e.KeyChar == (char)Keys.Return)
doSomething();
}
The only barcode scanner I have used (a USB model from Lindy) can append a return or not depending on how it is configured. Switching between modes is achieved by scanning a special control bar code printed on a leaflet provided with the scanner.
I'm not familiar with C# but in Java you can listen for an ActionEvent instead of a TextEvent to detect when return is pressed as opposed to a character being typed. This would be a simpler alternative to dandan78's suggestion, if it is available in C#.
Does the scanner not send a signal indicating it's completed reading the information? It surely would if it doesn't have a standard length of ending character. Anyway, you should read in the value into memory, and then set the textbox text at once rather than inserting each character as it's recieved.
Edit; If you're writing the information into a textbox as you recieve it, then calling the textbox event.. why bother writing it to the text box? Just call the event when you've determined it's a complete barcode directly
精彩评论