M Brian Dunson M Brian Dunson - 1 year ago 171
Vb.net Question

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

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.

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.

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

If Me.txtSearch.Focused = False Then
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.

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

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.

Answer Source

Change the code in your KeyPress event to:

    If Me.txtSearch.Focused = False Then
        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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download