12

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

问题:

如果我多次单击扫描仪,条形码会附加上一个值。

我的代码:

protected void txtBarcode_TextChanged(object sender, EventArgs e)
{
    string txt = this.txtBarcode.Text;
    this.txtBarcode.Text = string.Empty;
}
4

5 回答 5

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

我认为应该这样做。之所以有效,是因为 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>

然后这个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;
   });                                

});

似乎(至少在 Web 浏览器中)50 毫秒是字符之间允许的所需时间。我已经在 Firefox、Chrome 和 IE7 中对此进行了测试。

于 2010-05-24T07:02:18.523 回答
2

尝试将 TextChanged 事件处理程序更改为以下类型:

txtBarcode.SelectionStart = 0;  
txtBarcode.SelectionLength = txtBarcode.Text.Length;


读取代码后它将在文本框中选择文本并在其他读取时重写它。+ 更适合用户手动复制或更改

于 2010-05-24T07:01:23.100 回答
2

大多数扫描仪都可以在扫描后编程为“按回车”,请查看您的用户手册。您可以使用 Keypress 或 Keydown 事件处理程序来检查“输入”键并将其用作条形码的分隔符。如果您愿意,也可以使用特殊的分隔符。

 private void txtScan_KeyDown(object sender, KeyRoutedEventArgs e)
        {
            if (e.Key == Windows.System.VirtualKey.Enter)
            {
               //Do something here...

                txtScan.Text = "";
                txtScan.Focus(FocusState.Programmatic);
                e.Handled = true;  //keeps event from bubbling to next handler
            }
        }
于 2017-01-31T19:16:23.323 回答
0

<html>

<body>
  <script>
    var _lastRead = new Date();

    function Validate(control) {
      var _now = new Date();
      if ((_now - _lastRead) > 10) {
        control.value = "";
      }
      _lastRead = new Date();
    }
  </script>
  <input type="text" id="txtInput" onkeypress="Validate(this);" />
</body>

</html>

于 2019-07-08T20:26:39.017 回答
-1

如果您要分配txtBarcode.value += barcode,请将其更改为txtBarcode.value = barcode

于 2010-05-24T06:51:50.130 回答