public ComPort(string mPortName,PortInitInfo P) { ThePort = new SerialPort(mPortName, P._BaudRate, P._Parity, P._DataBits, P._StopBits); this.Open(); ThePort.ReadTimeout = 300; ThePort.WriteTimeout = 100; ThePort.DataReceived += new SerialDataReceivedEventHandler(ThePort_DataReceived); ThePort.ErrorReceived += new SerialErrorReceivedEventHandler(ThePort_ErrorReceived); }
public bool StartConnect() { PortInitInfo p = new PortInitInfo(9600, System.IO.Ports.Parity.None, 8, System.IO.Ports.StopBits.One); Com = new ComPort(SysPara.ComPort, p); if (Com.Open()) { connected = true; Program.WriteEventLog(this.GetType().FullName, string.Format("端口{0}打开成功!", SysPara.ComPort), ""); return true; } else { Program.WriteEventLog(this.GetType().FullName, string.Format("端口{0}打开失败!", SysPara.ComPort), ""); return false; } }
private void but_OpenCom_Click(object sender, EventArgs e) { but_OpenCom.Enabled = false; try { PortInitInfo p = new PortInitInfo(9600, System.IO.Ports.Parity.None, 8, System.IO.Ports.StopBits.One); cport = new ComPort(cbo_Port.Text, p); if (cport.Open()) { MessageBox.Show(string.Format("端口{0}打开成功!", cbo_Port.Text)); btn_Read.Enabled = true; } else { MessageBox.Show(string.Format("端口{0}打开失败!", cbo_Port.Text)); but_OpenCom.Enabled = true; } } catch(Exception ex) { MessageBox.Show(string.Format("端口{0}打开失败!-{1}", cbo_Port.Text,ex.Message)); but_OpenCom.Enabled = true; } }