自动将条码扫描仪输入发送到文本框 VB.Net / Winforms

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/19871583/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-17 15:45:52  来源:igfitidea点击:

Automatically send barcode scanner input to textbox VB.Net / Winforms

vb.netwinformsbarcode-scanner

提问by M Brian Dunson

I've reviewed dozens of options/solutions on this and I just can't get it to work.

我已经了许多关于此的选项/解决方案,但我无法让它发挥作用。

Simply put, I have a VB.Net Winform that has a textbox where a user can manually type in text or they can use a USB connected barcode scanner (that simulates a keyboard) to capture a UPC.

简而言之,我有一个 VB.Net Winform,它有一个文本框,用户可以在其中手动输入文本,或者他们可以使用 USB 连接的条形码扫描仪(模拟键盘)来捕获 UPC。

What I'm trying to do is get the barcode input to get entered into the textbox regardless of which control has the current focus.

我想要做的是让条形码输入进入文本框,无论哪个控件具有当前焦点。

I have set the KeyPreview property of the form to True.

我已将表单的 KeyPreview 属性设置为 True。

I then added some code to the frmMain_Keypress event as follows:

然后我向 frmMain_Keypress 事件添加了一些代码,如下所示:

    If Me.txtSearch.Focused = False Then
        txtSearch.Focus()
    End If

Very simple...and it works, sort of...

非常简单......它的工作原理,有点......

If txtSearch already has the focus, the entire barcode/UPC gets entered into the text box.

如果 txtSearch 已经具有焦点,则整个条码/UPC 将输入到文本框中。

However, if another control has the focus, every character of the barcode/UPC EXCEPT THE FIRST CHARACTERgets entered into the text box. It always strips off the first character.

但是,如果另一个控件具有焦点,则条形码/UPC 的每个字符除第一个字符外都会输入到文本框中。它总是去掉第一个字符。

I placed some debug statements in the above code to see if the initial character was being read at all and it is being read...just not sent to the text box.

我在上面的代码中放置了一些调试语句,以查看是否正在读取初始字符并且正在读取它......只是没有发送到文本框。

I've seen so many other REALLY complicated solutions to barcode scanning and it seems like I'm really close with something really simple, but, obviously it won't work if it strips the leading character.

我已经看到了许多其他非常复杂的条码扫描解决方案,看起来我真的很接近一些非常简单的东西,但是,显然,如果它去掉了主角,它就行不通了。

Hopefully I'm missing something very obvious.

希望我错过了一些非常明显的东西。

回答by endofzero

Change the code in your KeyPress event to:

将 KeyPress 事件中的代码更改为:

    If Me.txtSearch.Focused = False Then
        txtSearch.Focus()
        txtSearch.Text = e.KeyChar.ToString
        txtSearch.SelectionStart = txtSearch.Text.Length
        e.Handled = True
    End If

That way you capture the first key that comes in.

这样您就可以捕获进入的第一个键。