我正在使用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;
});
});
似乎(至少在Web浏览器中)50毫秒是允许字符之间所需的时间。我已经在Firefox,Chrome和IE7中对此进行了测试。
尝试将TextChanged事件处理程序更改为以下类型:
txtBarcode.SelectionStart = 0;
txtBarcode.SelectionLength = txtBarcode.Text.Length;
它将在读取代码后在文本框中选择文本,并在其他读取时重写。 +它更适合用户复制或手动更改
大多数扫描仪可以编程为扫描后“按下输入”,检查您的用户手册。您可以使用Keypress或Keydown事件处理程序检查“enter”键并将其用作条形码的分隔符。如果您愿意,也可以使用特殊的分隔符。
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
}
}
如果你要分配 txtBarcode.value += barcode
,改成它 txtBarcode.value = barcode