常用的扫描枪是一个实际上类似于即插即用的鼠标键盘的免驱动的HID设备,所以C#在识别扫描枪时,基本上跟识别键盘设备差不多
protected ScanerHook bar_code = new ScanerHook();
在加载窗体时调用bar_code.Start();打开
在关闭窗体时调用bar_code.Stop();关闭
具体驱动代码部分可留言暂无上传
/**********************************************************************
* 名称:BarCode_BarCodeEvent
* 功能:条形码扫描事件
* 输入:
* 输出:
* 说明:;
***********************************************************************/
private void ListenerScanerEvent(ScanerHook.ScanerCodes codes)
{
ShowInfo(codes);
}
/**********************************************************************
* 名称:ShowInfo
* 功能:显示扫描信息
* 输入:
* 输出:
* 说明:;
***********************************************************************/
private delegate void ShowInfoDelegate(ScanerHook.ScanerCodes _bar_code);
private void ShowInfo(ScanerHook.ScanerCodes _bar_code)
{
if (this.InvokeRequired)
{
this.BeginInvoke(new ShowInfoDelegate(ShowInfo), new object[] { _bar_code });
}
else
{
scan_code_str = _bar_code.Result;
ScanResultRichTextBox.Focus();
//产品0
if (product_test_select_index == 0)
{
if (product_storage_flag == false) //没有入库
{
if (sleep_test_result_ok_flag == false)
{
ControlInvokeHandle.NormalReceiveTextBoxInvoke(ScanResultRichTextBox, "测试数据获取中,请等待......", Color.Blue);
return;
}
SleepBeltScanCodeHandle(_bar_code.Result);
}
else
{
SleepBeltStorageOperation(_bar_code.Result);
}
}
//
else if (product_test_select_index == 1)
{
if (product_storage_flag == false) //没有入库
{
ScanResultRichTextBox.AppendText(_bar_code.Result + "\r\n");
}
else
{
}
}
//
else if (product_test_select_index == 2)
{
if (product_storage_flag == false) //没有入库
{
if (water_product_test_type_select == 0)
{
ScanResultRichTextBox.AppendText(_bar_code.Result + "\r\n");
water_scan_valid_flag = true;
Byte[] send_buffer;
ControlInvokeHandle.NormalSendData("::Bar Code:" + _bar_code.Result + "\r\n", false, Encoding.UTF8, out send_buffer);
CodeSerialPort.Write(send_buffer, 0, send_buffer.Length);
}
else if (water_product_test_type_select == 1)
{
WaterPrinttoMachineWorkInvoke(WaterProductMacPictureBox, _bar_code.Result);
}
}
else
{
}
}
//区域安全设备
else if (product_test_select_index == 3)
{
if (product_storage_flag == false) //没有入库
{
ScanResultRichTextBox.AppendText(_bar_code.Result + "\r\n");
}
else
{
AreaSafeStorageOperation(_bar_code.Result);
}
}
}
}
关于扫描枪进行扫描时的注意事项,扫描枪是一个HID输入设备,扫描枪扫描时,禁止或是想办法避免键盘的输入操作,否则键盘的操作内容会夹杂在扫描枪获取的条形码或是二维码内容中。
扫描枪进行扫描时,窗体中控件的焦点要移到按键操作无效的控件上,因为扫描枪扫描到内容后会在内容的末尾添加回车和换行符,控件焦点的问题会触发一些不相关的内容操作,比如误触发按键,比如给textbox控件写入内容