private void But_OpenPort_Click(object sender, EventArgs e) { if (PortName.Text == "") { MessageBox.Show("选择串口", "警告", MessageBoxButtons.OK, MessageBoxIcon.Warning); return; } if (m_SerialPort == null) { m_SerialPort = new SerialPortListener(PortName.Text, Convert.ToInt32(BaudRate.Text)); m_SerialPort.Parity = m_parity; m_SerialPort.StopBits = m_stopbits; m_SerialPort.DataBits = Convert.ToInt32(Com_DataBit.Text); m_SerialPort.BaudRate = Convert.ToInt32(BaudRate.Text); m_SerialPort.Handshake = Handshake.None; m_SerialPort.ReadBufferSize = 1024; m_SerialPort.ReceivedBytesThreshold = 1; m_SerialPort.BufferSize = 1024; m_SerialPort.ReceiveTimeout = Convert.ToInt32(TimeOut_Text.Text); m_SerialPort.WriteBufferSize = 100; m_SerialPort.SendInterval = 100; m_SerialPort.SerialPortResult += new HandResult(SerialPort_Result); m_SerialPort.OnSerialPortReceived += new OnReceivedData(SerialPort_Received); m_SerialPort.OnSeriaPortSend += new OnSendData(SerialPort_Send); } if (!m_SerialPort.IsOpen) { try { m_SerialPort.Start(); But_OpenPort.Text = "关闭串口"; Console.WriteLine($"serialport1.PortName = {m_SerialPort.PortName}"); Console.WriteLine($"serialport1.BaudRate = {m_SerialPort.BaudRate}"); Console.WriteLine($"serialport1.DataBits = {m_SerialPort.DataBits}"); Console.WriteLine($"serialport1.StopBits = {m_SerialPort.StopBits}"); Console.WriteLine($"serialport1.Parity = {m_SerialPort.Parity}"); state_Lable.Text = "串口已经打开"; } catch (Exception ex) { MessageBox.Show(ex.Message); } ThreadDataHandle = new Thread(new ThreadStart(Protocol_Resolution)); ThreadDataHandle.Priority = ThreadPriority.Lowest; ThreadDataHandle.Start(); } else { m_SerialPort.Stop(); if (m_SerialPort.IsOpen == false) { But_OpenPort.Text = "打开串口"; } state_Lable.Text = "串口已经打关闭"; } }
static void Main(string[] args) { SerialPortListener listener = new SerialPortListener("COM2"); listener.RawMessageRecieved += new EventHandler <RecievedMessageEventArgs>(listener_OnMessageRecieved); listener.Start(); Console.WriteLine(listener.ToString()); Console.WriteLine("Press ESC to exit"); do { while (!Console.KeyAvailable) { } } while (Console.ReadKey(true).Key != ConsoleKey.Escape); listener.Dispose(); }