我正在使用Scanner
(基本型号)扫描条形码。扫描的条形码将被捕获在文本框中。在 txtBarcode_TextChanged
事件中,我正在获取要访问的条码。
问题:
如果我多次点击扫描仪,条形码会附加上一个值。
我的代码:
protected void txtBarcode_TextChanged(object sender, EventArgs e)
{
string txt = this.txtBarcode.Text;
this.txtBarcode.Text = string.Empty;
}
最佳答案
条形码扫描器的问题在于它们通常看起来像标准的 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;
});
});
似乎(至少在网络浏览器中)50 毫秒是字符之间允许的所需时间。我已经在 Firefox、Chrome 和 IE7 中对此进行了测试。
关于c# - 文本框中的扫描值(使用扫描仪),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2895215/