首先,我要假设让扫描仪作为键盘驱动程序运行的原因是因为您没有SDK可以直接访问扫描仪数据。因此,这意味着当您敲击扫描枪上的扳机时,就让它模仿了在键盘上的打字。如果这将是一个正在进行的项目,建议您与扫描仪的制造商联系,以查看是否可以最好地获得SDK的副本,或者可以更好地获得其Windows驱动程序的源代码的副本,然后获取数据。直接从扫描仪。
其次,您发现看到回车键时试图立即处理输入并不能满足您的需求。我建议使用另一种方法。像这样的伪代码:
// 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.
}
上面的伪代码所做的是假定您从文本框中派生一个类并添加一个新的DataReady事件。然后,自定义文本框等待文本更改事件并启动计时器。如果更多输入持续快速进入,则计时器复位。如果没有更多输入输入,则计时器到期,并引发DataReady事件。然后,在包含该自定义控件的页面代码中,您等待DataReady事件。触发时,您可以将4条线拆分和合并为一条线,并进行其余的数据处理。
顺便说一句,为什么要像编写WinForms代码一样编写WPF代码?