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());
    }
}
相关推荐
AI科技星4 分钟前
全域数学·第三部·数术几何部·平行网格卷 完整专著目录(含拓扑发展史+学科定位·终稿)
c语言·开发语言·网络·量子计算·agi
SunnyDays10116 分钟前
Java 读写 Excel 公式:从基础到高级的实战总结
java·开发语言·excel
wb043072018 分钟前
Java 26
java·开发语言
白露与泡影11 分钟前
JVM GC调优实战:从线上频繁Full GC到RT降低80%的全过程
java·开发语言·jvm
灰灰勇闯IT12 分钟前
pyasc:用 Python 调用 CANN 的推理能力
开发语言·python
踏着七彩祥云的小丑13 分钟前
嵌入式测试学习第 17 天:常见接口:USB、Type-C、排针
单片机·嵌入式硬件
笨拙的老猴子1 小时前
[特殊字符] Java GC机制详解:G1、ZGC、Shenandoah全面解析与版本演进对比
java·开发语言
水木流年追梦1 小时前
大模型入门-Reward 奖励模型训练
开发语言·python·算法·leetcode·正则表达式
电子云与长程纠缠1 小时前
UE5制作六边形包裹球体效果
开发语言·python·ue5
砍材农夫1 小时前
物联网 基于netty构建mqtt协议规范(遗嘱与保留消息)
java·开发语言·物联网·netty