I think you've misunderstood how the event-driven model of Windows Forms applications work. When the barcode reader reads a barcode, it simply types the text of the barcode followed by the Return key. So you've presumably set it up so that the TextBox has keyboard focus, then when a barcode is read, the TextBox is typed into. Each time a 'key' is 'pressed' by the barcode reader, the KeyPress event is fired - I'm not entirely sure
You appear to be thinking that you 'pull' the keyboard presses from some kind of buffer when you call the event handler from within the DGV's CellContentClick event handler?
If I were you, I would start by writing a method that takes an identifier string as an argument and to start with maybe just adds it to a listbox:
vbnet Code:
Private Sub ProcessTrainIdentifier(ByVal identifier As String)
' For now, just log that we saw an identifier
ListBox1.Items.Add(String.Format("Saw identifier {0} at {1}", identifier, DateTime.Now))
End Sub
Now we can look at that KeyPress event handler. We're looking for the Return key being pressed, to indicate the end of the barcode reader's input. The normal way of doing this is to use the KeyDown event instead. That gives you the KeyCode property that is an enumeration of the keys on a keyboard and is a slightly better fit:
vbnet Code:
Private Sub TextBox1_KeyDown(sender As System.Object, e As System.Windows.Forms.KeyEventArgs) Handles TextBox1.KeyDown
If e.KeyCode = Keys.Return Then
' Do something
End If
End Sub
Remember that the TextBox has been typed into, so the preceeding input from the barcode reader is sitting in the TextBox. We can simply read the Text property, no need to handle each keypress and store in a string buffer. So what to do with our identifier? Pass it to the method that will process it. The only other thing we need to do is clear the TextBox so that we don't have the preceeding identifiers still in the TextBox when the barcode reader starts typing the next identifier it sees:
vbnet Code:
Private Sub TextBox1_KeyDown(sender As System.Object, e As System.Windows.Forms.KeyEventArgs) Handles TextBox1.KeyDown
If e.KeyCode = Keys.Return Then
ProcessTrainIdentifier(TextBox1.Text)
TextBox1.Clear()
End If
End Sub