private void SerialPort_DataReceived(object sender, SerialDataReceivedEventArgs e) { if (Closing_Flag) { return; } try { Listening_Flag = true; Array.Clear(receiveBuf, 0, receiveBuf.Length); int readCount = serialPort.BytesToRead; serialPort.Read(receiveBuf, 0, readCount); if (AntDataReceived != null) { AntDataReceived.Invoke(new string(receiveBuf)); } } catch (Exception ex) { if (AntDataReceived != null) { AntDataReceived.Invoke(string.Format("接收出错:{0}\r\n", ex.Message)); } } finally { Listening_Flag = false; } }
/// <summary> /// 关闭串口 /// </summary> public void CloseConnect() { try { Closing_Flag = true; while (Listening_Flag) { ; // Application.DoEvents(); } serialPort.DataReceived -= SerialPort_DataReceived; serialPort.Close(); } catch (Exception ex) { if (AntDataReceived != null) { AntDataReceived.Invoke(string.Format("{0}\r\n", ex.Message)); } } finally { dicSerialPort.Remove(serialPort.PortName); serialPort.Dispose(); } }
/// <summary> /// 打开串口 /// </summary> public void OpenConnect() { try { if (serialPort.IsOpen) { if (AntDataReceived != null) { AntDataReceived.Invoke(string.Format("{0}已打开!\r\n", serialPort.PortName)); } return; } Closing_Flag = false; // serialPort.ReadTimeout = 100; serialPort.ReadBufferSize = 1024; serialPort.Open(); serialPort.DataReceived += SerialPort_DataReceived; } catch (Exception ex) { if (AntDataReceived != null) { AntDataReceived.Invoke(string.Format("{0}\r\n", ex.Message)); } } }