WinForms Serial Port Handling Guide
One way to handle serial port data in WinForm is by using the SerialPort class in the System.IO.Ports namespace. Here is a simple example:
- Add a SerialPort control to a WinForm and configure the properties of the serial port, such as the port number, baud rate, and data bits.
- In the code of Form, you can handle serial port data through the events in the SerialPort class. Common events include DataReceived and ErrorReceived events.
- In the code of Form, you can use the methods in the SerialPort class to send and receive serial data. Commonly used methods include Write and ReadLine.
Here is an example code for handling serial data:
using System;
using System.IO.Ports;
using System.Windows.Forms;
namespace SerialPortExample
{
public partial class MainForm : Form
{
SerialPort serialPort;
public MainForm()
{
InitializeComponent();
}
private void MainForm_Load(object sender, EventArgs e)
{
// 初始化串口
serialPort = new SerialPort("COM1", 9600, Parity.None, 8, StopBits.One);
serialPort.DataReceived += SerialPort_DataReceived;
serialPort.ErrorReceived += SerialPort_ErrorReceived;
// 打开串口
try
{
serialPort.Open();
}
catch (Exception ex)
{
MessageBox.Show("串口打开失败:" + ex.Message);
}
}
private void SerialPort_DataReceived(object sender, SerialDataReceivedEventArgs e)
{
// 接收串口数据
string data = serialPort.ReadLine();
// 处理接收到的数据
// ...
// 在界面上显示接收到的数据
this.Invoke(new Action(() =>
{
textBoxReceived.Text = data;
}));
}
private void SerialPort_ErrorReceived(object sender, SerialErrorReceivedEventArgs e)
{
// 处理串口错误
// ...
}
private void buttonSend_Click(object sender, EventArgs e)
{
// 发送串口数据
string data = textBoxSend.Text;
// 发送数据
serialPort.Write(data);
}
private void MainForm_FormClosing(object sender, FormClosingEventArgs e)
{
// 关闭串口
serialPort.Close();
}
}
}
In the above code, the serial port is initialized and opened in the MainForm_Load event, received serial port data is processed and displayed on the interface in the SerialPort_DataReceived event, serial port data is sent in the buttonSend_Click event, and the serial port is closed in the MainForm_FormClosing event.