文本框中的扫描值(使用扫描仪)

Gee*_*eth 11 javascript c# jquery web-applications barcode-scanner

我正在使用Scanner(基本型号)来扫描条形码.扫描的条形码将在文本框中捕获.在txtBarcode_TextChanged事件中,我正在获取要访问的条形码.

问题:

如果我多次点击扫描仪,条形码会附加前一个值.

码:

 protected void txtBarcode_TextChanged(object sender, EventArgs e)
    {
        string txt = this.txtBarcode.Text;
        this.txtBarcode.Text = string.Empty;
    }
Run Code Online (Sandbox Code Playgroud)

Kaz*_*zar 9

条形码扫描仪的用途是它们通常看起来像标准的HID键盘.因此,扫描的每个新代码在前一个之后被有效地"键入".我过去使用的解决方案是查看该文本框中按键之间经过的时间.如果它超过10毫秒(或大约该值,我相信这是我用来'键入'整个代码的扫描仪所花费的最大时间),那么它是一个新的条形码,你应该删除它之前的所有内容.

我还没有IDE可供使用,因此大多数类/方法名称可能都没有了,但是像一个例子:

DateTime lastKeyPress = DateTime.Now;

void txtBarcode_KeyPress(object sender, KeyPressEventArgs args)
{

   if(((TimeSpan) (DateTime.Now - lastKeyPress)).TotalMilliseconds > 10)
   {
     txtBarcode.Text = "";      
   }
   lastKeyPress = DateTime.Now;
}
Run Code Online (Sandbox Code Playgroud)

我认为应该这样做.它的工作原理是因为KeyPress事件发生在附加字符之前,因此您可以先清除文本框.

编辑:要设置,我想无论你有什么txtBarcode.TextChanged += txtBarcode_TextChanged,你都有一个txtBarcode.KeyPress += txtBarcode_KeyPress.检查事件名称是否正确.

编辑2:


jQuery版本:

假设这个HTML(因为您使用的是ASP,输入标记的源代码看起来会有所不同,但输出仍然具有id属性,这实际上是唯一重要的属性):

   <form action="" method="post">
        <input type="text" name="txtBarcode" id="txtBarcode" />
    </form>
Run Code Online (Sandbox Code Playgroud)

然后这个JavaScript工作:

$(document).ready(function() {

   var timestamp = new Date().getTime();

   $("#txtBarcode").keypress(function(event)
   {
        var currentTimestamp = new Date().getTime();

        if(currentTimestamp - timestamp > 50)
        {
            $(this).val("");
        }
        timestamp = currentTimestamp;
   });                                

});
Run Code Online (Sandbox Code Playgroud)

似乎(至少在Web浏览器中)50毫秒是允许字符之间所需的时间.我在Firefox,Chrome和IE7中测试了这个.