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());
    }
}
相关推荐
SaleCoder42 分钟前
用Python构建机器学习模型预测股票趋势:从数据到部署的实战指南
开发语言·python·机器学习·python股票预测·lstm股票模型·机器学习股票趋势
zero自由如风5 小时前
STM32裸机开发(中断,轮询,状态机)与freeRTOS
stm32·单片机·嵌入式硬件
玩代码6 小时前
备忘录设计模式
java·开发语言·设计模式·备忘录设计模式
技术猿188702783517 小时前
实现“micro 关键字搜索全覆盖商品”并通过 API 接口提供实时数据(一个方法)
开发语言·网络·python·深度学习·测试工具
放飞自我的Coder7 小时前
【colab 使用uv创建一个新的python版本运行】
开发语言·python·uv
艾莉丝努力练剑8 小时前
【数据结构与算法】数据结构初阶:详解顺序表和链表(四)——单链表(下)
c语言·开发语言·数据结构·学习·算法·链表
zyhomepage8 小时前
科技的成就(六十九)
开发语言·网络·人工智能·科技·内容运营
珊瑚里的鱼8 小时前
第十三讲 | map和set的使用
开发语言·c++·笔记·visualstudio·visual studio
逑之8 小时前
C++笔记1:命名空间,缺省参数,引用等
开发语言·c++·笔记
songroom8 小时前
【转】Rust: PhantomData,#may_dangle和Drop Check 真真假假
开发语言·后端·rust