using System; using System.Collections.Generic; using System.IO.Ports; using System.Linq; using System.Text; using System.Windows; namespace UAS_MES.PublicMethod { /// /// 从串口获取数据 /// class ReadDataFromSerialPort { static List OpenPort = new List(); SerialPort serial = new SerialPort(); string SerialPort; public ReadDataFromSerialPort(string Port) { if (!OpenPort.Contains(Port)) { try { SerialPort = Port; serial.PortName = Port; OpenPort.Add(Port); serial.DataReceived += Serial_DataReceived; serial.Open(); } catch (Exception ex) { MessageBox.Show(ex.Message); } } else MessageBox.Show(Port + "已开启,请勿重复打开"); } private void Serial_DataReceived(object sender, SerialDataReceivedEventArgs e) { } /// /// 读取串口数据 /// /// public string Read() { string Data = ""; if (serial.IsOpen) { try { Data = serial.ReadLine(); serial.DiscardInBuffer(); } catch (Exception e) { MessageBox.Show(e.Message); } } return Data; } /// /// 如果打开的串口不为空则进行关闭 /// public void Close() { if (serial.IsOpen) { serial.Close(); OpenPort.Remove(SerialPort); } } } }