.NET WinForm读取扫描枪从COM口传过来的数据,显示在TextBox中,并做其他操作。
1 private string portName = ""; //串口 2 private int baudRate = 0; //速率 3 private int dataBits = 0; //数据位 4 int scanNum = 0; 5 int noRead = 0; 6 string strReceive = ""; 7 string serialNumber = ""; 8 string url = ""; 9 int SocketPort = 0; 10 bool isDispose = false;//是否在处理COM数据,true为正在处理,false空闲 11 private void DataReceived(object sender, SerialDataReceivedEventArgs e) 12 { 13 try 14 { 15 strReceive = ReadCOM.serialport.ReadExisting(); 16 if (string.IsNullOrEmpty(strReceive)) 17 { 18 return; 19 } 20 else 21 { 22 if (!isDispose) 23 { 24 BackgroundWorker bgWorker = new BackgroundWorker(); 25 bgWorker.DoWork += new DoWorkEventHandler(bgWorker_DoWork); 26 bgWorker.RunWorkerAsync(strReceive); 27 return; 28 } 29 } 30 } 31 catch (System.Exception ex) 32 { 33 throw new Exception(ex.Message); 34 } 35 36 } 37 private void bgWorker_DoWork(object sender, DoWorkEventArgs e) 38 { 39 isDispose = true; 40 this.Invoke((EventHandler)(delegate 41 { 42 this.txtGlassID.Text = strReceive; 43 this.txtGlassID.Refresh(); 44 KeyEventArgs ev = new KeyEventArgs(Keys.Enter); 45 txtGlassID_KeyDown(sender, ev); 46 isDispose = false; 47 48 })); 49 } 50 private void OpenPort() 51 { 52 if (ReadCOM.serialport.IsOpen) 53 { 54 ReadCOM.serialport.Close(); 55 } 56 ReadCOM.serialport.PortName = portName; 57 ReadCOM.serialport.BaudRate = baudRate; 58 ReadCOM.serialport.Parity = Parity.None; 59 ReadCOM.serialport.DataBits = dataBits; 60 ReadCOM.serialport.StopBits = StopBits.One; 61 //打开串口 62 ReadCOM.serialport.Open(); 63 64 } 65 try 66 { 67 // serialport.DataReceived = null; 68 //if (serialport != null ) 69 //{ 70 // serialport.Clofse(); 71 //} 72 //serialport = new SerialPort(); 73 ReadCOM.serialport.DataReceived += DataReceived; 74 portName = ConfigurationManager.AppSettings["PortName"].ToString(); 75 baudRate = int.Parse(ConfigurationManager.AppSettings["BaudRate"]); 76 dataBits = int.Parse(ConfigurationManager.AppSettings["DataBits"]); 77 serialNumber = ConfigurationManager.AppSettings["SerialNumber"].ToString(); 78 SocketPort = int.Parse(ConfigurationManager.AppSettings["SocketPort"]); 79 this.OpenPort(); 80 //this.GetReaderStatu(); 81 } 82 catch (System.Exception ex) 83 { 84 // MessageBox.Show("程序已启动或串口已被占用!"); 85 MessageBox.Show(ex.Message); 86 }
Android 成长之路