using HMI.UI.Entity; using System; using System.Collections.Generic; using System.IO.Ports; using System.Windows.Controls; namespace Plugin.TsExecution { public class ScannerManager { public static Dictionary map = new Dictionary(); public static Dictionary> controlMap = new Dictionary>(); public static Dictionary focusMap = new Dictionary(); public static Dictionary reverseMap = new Dictionary(); public static void RegisterCom(ScannerConfig setting, TextBox tb) { if (!map.ContainsKey(setting.PortName)) { // 配置串口 var serialPort = new SerialPort { PortName = setting.PortName, BaudRate = setting.BaudRate, Parity = Parity.None, DataBits = setting.DataBits, StopBits = setting.StopBits, Handshake = Handshake.None, DtrEnable = setting.DtrEnable, RtsEnable = setting.RtsEnable //ReadTimeout = 500, //WriteTimeout = 500, //ReciveBufferSize=4096 }; try { // 打开串口 serialPort.Open(); map[setting.PortName] = serialPort; controlMap[serialPort] = new Queue(); reverseMap[tb] = serialPort; tb.GotFocus += Tb_GotFocus; controlMap[serialPort].Enqueue(tb); // 注册接收数据事件 serialPort.DataReceived += SerialPort_DataReceived; ; } catch (Exception ex) { } } else { } } private static string ReadDataFrom(SerialPort sp) { string barcode = ""; while (sp.BytesToRead > 0) { byte[] buffer = new byte[sp.BytesToRead]; sp.Read(buffer, 0, buffer.Length); barcode += System.Text.Encoding.UTF8.GetString(buffer); System.Threading.Thread.Sleep(50); } return barcode; } private static void SerialPort_DataReceived(object sender, SerialDataReceivedEventArgs e) { var sp = sender as SerialPort; string barcode = ReadDataFrom(sp); TextBox tb; if (focusMap.ContainsKey(sp)) { tb = focusMap[sp]; } else { tb = controlMap[sp].Dequeue(); } //string barcode = tb.Dispatcher.Invoke(() => { tb.Text = barcode; }); } private static void Tb_GotFocus(object sender, System.Windows.RoutedEventArgs e) { var tb = sender as TextBox; SerialPort sp = reverseMap[tb]; focusMap[sp] = tb; } } }