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());
    }
}
相关推荐
上海合宙LuatOS6 分钟前
全栈工程师实战手册:LuatOS日志系统开发指南!
java·开发语言·单片机·嵌入式硬件·物联网·php·硬件工程
多敲代码防脱发7 分钟前
导出导入Excel文件(详解-基于EasyExcel)
java·开发语言·jvm·数据库·mysql·excel
公子无缘13 分钟前
【嵌入式】记一次解决VScode+PlatformIO安装卡死的经历
vscode·stm32·单片机·mcu·platformio
昊昊昊昊昊明26 分钟前
十天学会嵌入式技术之51单片机—day-9
单片机·嵌入式硬件·51单片机
来自星星的坤1 小时前
深入理解 NumPy:Python 科学计算的基石
开发语言·python·numpy
小声读源码1 小时前
【技巧】使用UV创建python项目的开发环境
开发语言·python·uv·dify
yxc_inspire1 小时前
基于Qt的app开发第七天
开发语言·c++·qt·app
zm-v-159304339861 小时前
解锁遥感数据密码:DeepSeek、Python 与 OpenCV 的协同之力
开发语言·python·opencv
周Echo周2 小时前
20、map和set、unordered_map、un_ordered_set的复现
c语言·开发语言·数据结构·c++·算法·leetcode·list
明天更新2 小时前
Java处理压缩文件的两种方式!!!!
java·开发语言·7-zip