winform串口控件serialPort1的使用
serialPort1 控件使用的关键点主要有三:
1、配置串口号
2、配置数据接收事件
3、打开串口
关键代码如下:
1 private void Form1_Load(object sender, EventArgs e) 2 { 3 serialPort1.PortName = "COM1"; 4 serialPort1.DataReceived += SerialPort1_DataReceived; 5 serialPort1.Open(); 6 } 7 8 private void SerialPort1_DataReceived(object sender, System.IO.Ports.SerialDataReceivedEventArgs e) 9 { 10 try 11 { 12 int len = serialPort1.BytesToRead; 13 Byte[] buf = new byte[len]; 14 int length = serialPort1.Read(buf, 0, len); 15 string result = System.Text.Encoding.ASCII.GetString(buf); 16 UpdateTextBox(result); 17 } 18 catch (Exception ex) 19 { 20 UpdateTextBox(ex.Message); 21 } 22 23 }