First, I'm going to assume that the reason why you are letting the scanner run as keyboard driver is because you don't have the SDK to access the scanner data directly. So that means when you hit the trigger on the scanner gun, you are letting it emulate typing into the keyboard. If this is going to be an ongoing project, I would recommend contacting the manufacturer of your scanner and see if you can a copy of the SDK at best, or a copy of the source code for their Windows drivers at worse and then get the data directly from the scanner.
Second, as you've discovered trying to process the input right away when you see the Return key come in is not getting you what you need. I would suggest a different approach. Something like this pseudo code:
// In view code:
public ScannerInputTextBox : TextBox
{
public event EventHandler DataReady;
ScannerInputTextBox()
: base()
{
:
isWaitingForInput = true;
timer = new DispatcherTimer();
timer.Tick += (o,e) => FireDataReadyEvent();
timer.Interval = TimeSpan.FromSeconds(1); // wait for input to complete in 1 second
}
OnTextChange()
{
if (!isWaitingForInput)
return;
// reset the timer to keep waiting
timer.Stop();
timer.Start();
}
FireDataReadyEvent()
{
isWaitingForInput = false;
timer.Stop();
DataReady?.Invoke(...);
isWaitingForInput = true;
}
} // end of custom ScannerInputTextBox control
// In your view model code:
InputViewModel()
{
scannerInputTextBox.DataReady += (o, e) => OnDataReady;
}
OnDataReady()
{
var fourLineText = scannerInputTextBox.Text.Split('\n');
var joinedText = string.Join("", fourLineText);
scannerInputTextBox.Text = joinedText;
// do rest of processing of joinedText to do your database queries, etc.
}
What the pseudo code above does is that it assumes that you derive a class from the text box and add a new DataReady event. The custom textbox then waits for text change events and starts a timer. If more input keeps coming in rapidly, the timer is reset. If no more input comes in, the timer expires, and the DataReady event is fired. Then in your page code that contains that custom control, you wait for the DataReady event. When it fires, then you can do the splitting and joining of the 4 lines into a single line, as well as do the rest of your data processing.
As an aside, why are you writing WPF code as if you were writing WinForms code?