How to send and receive data through a WinForm serial port?

In WinForm, you can use the SerialPort class for serial communication to send and receive data. Here is a simple example:

  1. Firstly, in the WinForm design view, drag a SerialPort control onto the form.
  2. Add the following code to the code file of the window form:
using System;
using System.IO.Ports;

namespace SerialPortDemo
{
    public partial class Form1 : Form
    {
        SerialPort serialPort;

        public Form1()
        {
            InitializeComponent();

            // 初始化SerialPort对象
            serialPort = new SerialPort();
            serialPort.BaudRate = 9600; // 设置波特率
            serialPort.DataBits = 8; // 设置数据位
            serialPort.Parity = Parity.None; // 设置奇偶校验位
            serialPort.StopBits = StopBits.One; // 设置停止位
            serialPort.DataReceived += SerialPort_DataReceived; // 绑定数据接收事件
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            // 获取可用的串口列表,并添加到ComboBox控件中
            string[] ports = SerialPort.GetPortNames();
            comboBox1.Items.AddRange(ports);
        }

        private void buttonOpen_Click(object sender, EventArgs e)
        {
            if (!serialPort.IsOpen)
            {
                try
                {
                    serialPort.PortName = comboBox1.SelectedItem.ToString(); // 设置串口名称
                    serialPort.Open(); // 打开串口
                    buttonOpen.Enabled = false;
                    buttonClose.Enabled = true;
                }
                catch (Exception ex)
                {
                    MessageBox.Show(ex.Message);
                }
            }
        }

        private void buttonClose_Click(object sender, EventArgs e)
        {
            if (serialPort.IsOpen)
            {
                serialPort.Close(); // 关闭串口
                buttonOpen.Enabled = true;
                buttonClose.Enabled = false;
            }
        }

        private void buttonSend_Click(object sender, EventArgs e)
        {
            if (serialPort.IsOpen)
            {
                serialPort.Write(textBoxSend.Text); // 发送数据
            }
        }

        private void SerialPort_DataReceived(object sender, SerialDataReceivedEventArgs e)
        {
            string data = serialPort.ReadExisting(); // 读取接收到的数据
            // 在UI线程中更新UI控件上的数据
            Invoke(new Action(() =>
            {
                textBoxReceive.Text += data;
            }));
        }
    }
}

In the example above, we use the SerialPort control to transmit and receive data through a serial port. Upon loading the form, we retrieve a list of available serial ports and add them to a ComboBox control. When the user clicks the “Open” button, we open the selected serial port. When the user clicks the “Close” button, we close the serial port. When the user clicks the “Send” button, we send the text data from the TextBox. When data is received, we use the DataReceived event to read the received data and display it in the TextBox.

It is important to note that the configuration parameters of the serial port (baud rate, data bits, parity bit, stop bits) need to be set according to the actual situation. Additionally, in order to update data on UI controls in the data reception event handler, we use the Invoke method to perform the update operation on the UI thread.

bannerAds