C#高速串口通讯方案winform实例

C#高速串口通讯方案winform实例

python 复制代码
using System;
using System.IO.Ports;
using System.Threading;
using System.Windows.Forms;

public class SerialPortForm : Form
{
    private ComboBox cboPorts;
    private Button btnConnect;
    private Button btnSend;
    private TextBox txtMessage;
    private RichTextBox rtbReceiver;

    private SerialPort serialPort;
    private System.Threading.Timer uiUpdateTimer;

    public SerialPortForm()
    {
        this.Text = "串口通讯窗体";
        this.Size = new System.Drawing.Size(400, 300);

        cboPorts = new ComboBox();
        cboPorts.Location = new System.Drawing.Point(20, 20);
        cboPorts.DropDownStyle = ComboBoxStyle.DropDownList;

        btnConnect = new Button();
        btnConnect.Text = "连接";
        btnConnect.Location = new System.Drawing.Point(150, 20);
        btnConnect.Click += BtnConnect_Click;

        txtMessage = new TextBox();
        txtMessage.Location = new System.Drawing.Point(20, 60);
        txtMessage.Width = 250;

        btnSend = new Button();
        btnSend.Text = "发送";
        btnSend.Location = new System.Drawing.Point(280, 60);
        btnSend.Click += BtnSend_Click;

        rtbReceiver = new RichTextBox();
        rtbReceiver.Location = new System.Drawing.Point(20, 100);
        rtbReceiver.Width = 350;
        rtbReceiver.Height = 150;

        this.Controls.Add(cboPorts);
        this.Controls.Add(btnConnect);
        this.Controls.Add(txtMessage);
        this.Controls.Add(btnSend);
        this.Controls.Add(rtbReceiver);

        LoadAvailablePorts();
    }

    private void LoadAvailablePorts()
    {
        string[] ports = SerialPort.GetPortNames();
        cboPorts.Items.AddRange(ports);
        if (ports.Length > 0)
            cboPorts.SelectedIndex = 0;
    }

    private void BtnConnect_Click(object sender, EventArgs e)
    {
        if (serialPort == null)
        {
            serialPort = new SerialPort(cboPorts.SelectedItem.ToString(), 9600);
            serialPort.DataReceived += SerialPort_DataReceived;

            try
            {
                serialPort.Open();
                MessageBox.Show("连接成功!");
                uiUpdateTimer = new System.Threading.Timer(UpdateUI, null, 0, 20); // 每20ms更新UI
            }
            catch (Exception ex)
            {
                MessageBox.Show("连接失败: " + ex.Message);
            }
        }
        else
        {
            MessageBox.Show("已经连接到串口!");
        }
    }

    private void BtnSend_Click(object sender, EventArgs e)
    {
        if (serialPort != null && serialPort.IsOpen)
        {
            serialPort.WriteLine(txtMessage.Text);
        }
        else
        {
            MessageBox.Show("请先连接串口!");
        }
    }

    private void SerialPort_DataReceived(object sender, SerialDataReceivedEventArgs e)
    {
        // 收到数据后不直接更新UI,先存储数据
    }

    private void UpdateUI(object state)
    {
        if (serialPort != null && serialPort.IsOpen)
        {
            string data = serialPort.ReadExisting();
            if (!string.IsNullOrEmpty(data))
            {
                rtbReceiver.Invoke(new Action(() => rtbReceiver.AppendText(data + Environment.NewLine)));
            }
        }
    }

    protected override void OnFormClosing(FormClosingEventArgs e)
    {
        uiUpdateTimer?.Change(Timeout.Infinite, Timeout.Infinite); // 停止定时器
        uiUpdateTimer?.Dispose();
        
        if (serialPort != null && serialPort.IsOpen)
        {
            serialPort.Close();
        }
        base.OnFormClosing(e);
    }

    [STAThread]
    public static void Main()
    {
        Application.EnableVisualStyles();
        Application.Run(new SerialPortForm());
    }
}
相关推荐
White の algo2 分钟前
【C++初阶】内存管理
开发语言·c++
iuhart9 分钟前
Golang中的 “...” 操作符
开发语言·golang
敖行客 Allthinker12 分钟前
Go 语言中 panic 和 recover 的代价:性能与设计的权衡
开发语言·后端·golang
今天也想MK代码1 小时前
rust编程实战:实现3d粒子渲染wasm
开发语言·rust·wasm
summer__77771 小时前
案例1_1:Proteus点亮8个蓝色LED灯
单片机·proteus
结衣结衣.1 小时前
【Qt】自定义信号和槽函数
开发语言·c++·qt·c++11
尘鹄2 小时前
一文讲懂Go语言如何使用配置文件连接数据库
开发语言·数据库·后端·golang
qq_433554542 小时前
C++ 二叉搜索树代码
开发语言·c++·算法
好看资源平台2 小时前
手写识别革命:Manus AI如何攻克多语言混合识别难题(二)
开发语言·人工智能·php
Hopebearer_2 小时前
vue3中ref和reactive的区别
开发语言·前端·javascript·vue.js·前端框架·ecmascript