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());
    }
}
相关推荐
HarrisHaword23 分钟前
JAVA 导出 word
java·开发语言·word
PingdiGuo_guo28 分钟前
C++指针(四)万字图文详解!
开发语言·c++
s91236010129 分钟前
Rust Command无法执行*拓展解决办法
开发语言·后端·rust
pk_xz12345635 分钟前
MATLAB编写的机械臂控制仿真程序,它主要实现了对一个二连杆机械臂的运动控制仿真,比较了PID控制和非线性模型预测控制两种方法在机械臂轨迹跟踪任务中的性能
开发语言·matlab
2301_7875528743 分钟前
aidigu开源微博项目程序,PHP开发的开源微博系统,自媒体个人创业、网盘推广首先
开发语言·开源·php·数据库开发·媒体
khazix1011 小时前
【C语言】--- 文件操作
c语言·开发语言
我不是程序猿儿1 小时前
【C#】一种优雅的基于winform的串口通信管理
stm32·单片机·c#
zhangxueyi1 小时前
图解Java实现冒泡排序(Bubble Sort)
java·开发语言
麦麦Max1 小时前
STL-函数对象
开发语言·c++·算法
仙人掌_lz1 小时前
使用Python从零实现一个端到端多模态 Transformer大模型
开发语言·人工智能·python·ai·transformer·多模态