using log4net; using System.IO.Ports; namespace Aucma.Core.ScannerGun { /// /// 扫码枪初始化 /// public class ScannerGunService : IScannerGunService { private static readonly log4net.ILog log = LogManager.GetLogger(typeof(ScannerGunService)); public void ScannerGunAsync() { //COM口初始化 InitScanCode(); } /// 初始化扫码设备 采用COM连接 /// public static void InitScanCode() { string COM1 = "COM4"; InstanceSerialPort3(COM1); } public static void InstanceSerialPort3(string portName) { //实例化串行端口 SerialPort serialPort = new SerialPort(); //端口名 注:因为使用的是USB转RS232 所以去设备管理器中查看一下虚拟com口的名字 serialPort.PortName = portName; //波特率 serialPort.BaudRate = 9600; //奇偶校验 serialPort.Parity = Parity.None; //停止位 serialPort.StopBits = StopBits.One; //数据位 serialPort.DataBits = 8; //忽略null字节 serialPort.DiscardNull = true; //接收事件 serialPort.DataReceived += serialPort_DataReceived; //开启串口 serialPort.Open(); } /// /// 接收数据 /// /// /// static void serialPort_DataReceived(object sender, SerialDataReceivedEventArgs e) { try { //防止数据接收不完整 线程sleep(1000) System.Threading.Thread.Sleep(1000); SerialPort serialPort = (SerialPort)sender; //开启接收数据线程 Thread threadReceiveSub = new Thread(new ParameterizedThreadStart(ReceiveData)); threadReceiveSub.Start(serialPort); } catch (Exception ex) { throw; } } private static void ReceiveData(object serialPortobj) { try { SerialPort serialPort = (SerialPort)serialPortobj; string code = serialPort.ReadExisting(); if (string.IsNullOrEmpty(code)) { return; } //业务处理 Console.WriteLine(code.Trim()); } catch (Exception ex) { log.Error(ex.Message); } } } }