public SerialPort InitSerialPort() { if (SerialPort1 == null) { SerialPort1 = new SerialPort(); } string[] slist = System.IO.Ports.SerialPort.GetPortNames(); SerialPortNameList.Clear(); foreach (var item in slist) { SerialPortNameList.Add(item); } if (SerialPortNameList.Count > 0) { SerialPortName = SerialPortNameList[0]; } else { System.Windows.MessageBox.Show("没有串口可用!"); return(null); } if (NotifyMessage == null) { SerialPort1.DataReceived += SerialPort1_DataReceived; } return(SerialPort1); }
/// <summary> 第一步,初始化 </summary> /// <returns> </returns> public SerialPort InitSerialPort() { if (SerialPort1 == null) { SerialPort1 = new SerialPort(); } //通过WMI获取COM端口 //string[] slist = Helpers.HardwareInfoHelper. MulGetHardwareInfo(Helpers.HardwareEnum.Win32_PnPEntity, "Name"); string[] slist = System.IO.Ports.SerialPort.GetPortNames(); SerialPortNameList.Clear(); foreach (var item in slist) { SerialPortNameList.Add(item); } if (SerialPortNameList.Count > 0) { SerialPortName = SerialPortNameList[0]; } else { System.Windows.MessageBox.Show("没有串口可用!"); return(null); } SerialPort1.BaudRate = Baudrate; SerialPort1.Parity = (Parity)Parity; SerialPort1.DataBits = (int)DataBit; SerialPort1.StopBits = (StopBits)StopBit; if (WriteTimeout != 0) { SerialPort1.WriteTimeout = WriteTimeout; } else { SerialPort1.WriteTimeout = 3000; } if (ReadTimeout != 0) { SerialPort1.ReadTimeout = ReadTimeout; } else { SerialPort1.ReadTimeout = 10000; } return(SerialPort1); }