Uart_Prj02 Windows 窗口版串口_Step4

 OK!完成了!

1.上位机界面和8088单板机的通讯中断

2.程序

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO.Ports;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;
//using HORSES; // 注意大小写,通常命名空间首字母大写

namespace UartApp2
{
    public partial class Form1 : Form
    {
        private SerialPort _serialPort;
        private Thread _sendThread;
        private bool _isSending = false;
        private bool _isRunning = true;
        private int _sendCount = 0;
        private int _receiveCount = 0;
        public Form1()
        {
            InitializeComponent();
            InitializeForm();
            //InitializeSerialPort();
        }
        private void InitializeForm()
        {
            // 设置窗体属性
            this.Text = "串口通信工具 - COM8 @ 9600 bps";
            this.Size = new Size(800, 600);
            //this.BackColor = Color.AliceBlue;///Color.FromArgb(45, 45, 48);
            this.BackColor = Color.FromArgb(45,45,48);
            this.ForeColor = Color.White;
            this.FormClosing += MainForm_FormClosing;//这行代码在 C# Windows 窗体应用程序中扮演着重要角色,用于处理窗体关闭前的操作。
                                                     // this.FormClosing+=
                                                     // 创建控件
            var titleLabel = new Label
            {
                Text = "串口通信工具",
                Font = new Font("Segoe UI", 18, FontStyle.Bold),
                ForeColor = Color.LightSkyBlue,
                AutoSize = true,
                Location = new Point(20, 20)
            };

            var configLabel = new Label
            {
                Text = "配置: COM8, 9600 bps, 8N1",
                Font = new Font("Segoe UI", 10),
                AutoSize = true,
                Location = new Point(20, 60)
            };

              var statusLabel = new Label
            {
                Text = "状态: 未启动",
                Font = new Font("Segoe UI", 10),
                AutoSize = true,
                Location = new Point(20, 90),
                ForeColor = Color.LightCoral
            };

            var sendButton = new Button
            {
                Text = "启动发送",
                Font = new Font("Segoe UI", 10),
                Size = new Size(120, 40),
                Location = new Point(20, 130),
                BackColor = Color.FromArgb(0, 122, 204),
                FlatStyle = FlatStyle.Flat
            };
            sendButton.FlatAppearance.BorderSize = 0;
            sendButton.Click += SendButton_Click;
            var clearButton = new Button
            {
                Text = "清空显示",
                Font = new Font("Segoe UI", 10),
                Size = new Size(120, 40),
                Location = new Point(150, 130),
                BackColor = Color.FromArgb(63, 63, 70),
                FlatStyle = FlatStyle.Flat
            };
            clearButton.FlatAppearance.BorderSize = 0;
            clearButton.Click += ClearButton_Click;
            var statsLabel = new Label
            {
                Text = "发送: 0 | 接收: 0",
                Font = new Font("Segoe UI", 10),
                AutoSize = true,
                Location = new Point(300, 140)
            };

            var receiveLabel = new Label
            {
                Text = "接收数据:",
                Font = new Font("Segoe UI", 10),
                AutoSize = true,
                Location = new Point(20, 190)
            };

            var receiveBox = new RichTextBox
            {
                Font = new Font("Consolas", 10),
                Size = new Size(740, 340),
                Location = new Point(20, 220),
                BackColor = Color.FromArgb(30, 30, 30),
                ForeColor = Color.Lime,
                ReadOnly = true,
                ScrollBars = RichTextBoxScrollBars.Vertical
            };

            // 添加到窗体
            this.Controls.Add(titleLabel);
            this.Controls.Add(configLabel);
            this.Controls.Add(statusLabel);
            this.Controls.Add(sendButton);
            this.Controls.Add(clearButton);
            this.Controls.Add(statsLabel);
            this.Controls.Add(receiveLabel);
            this.Controls.Add(receiveBox);

            // 保存控件引用
            this.Controls.Add(new ControlReference(statusLabel, statsLabel, receiveBox));


        }

        private void InitializeSerialPort()
        {
            try
            {
                _serialPort = new SerialPort("COM8", 9600, Parity.None, 8, StopBits.One)
                {
                    Handshake = Handshake.None,
                    ReadTimeout = 500,
                    WriteTimeout = 500,
                    Encoding = System.Text.Encoding.ASCII
                };

                _serialPort.Open();
                _serialPort.DataReceived += SerialPort_DataReceived;

                 UpdateStatus("串口已连接", Color.LightGreen);
                //MessageBox.Show("串口已连接");
            }
            catch (Exception ex)
            {
                UpdateStatus($"错误: {ex.Message}", Color.Red);
                //MessageBox.Show($"错误: {ex.Message}");
            }
        }

        // 辅助方法
        private void UpdateStatus(string message, Color color)
        {
            this.Invoke((MethodInvoker)delegate {
                var refs = GetControlReferences();
                refs.StatusLabel.Text = $"状态: {message}";
                refs.StatusLabel.ForeColor = color;
            });
        }

        private void SerialPort_DataReceived(object sender, SerialDataReceivedEventArgs e)
        {
            try
            {
                if (_serialPort.BytesToRead > 0)
                {
                    string data = _serialPort.ReadExisting();
                    _receiveCount += data.Length;

                    // 更新UI
                    this.Invoke((MethodInvoker)delegate {
                        var refs = GetControlReferences();
                        refs.ReceiveBox.AppendText(data);
                        refs.ReceiveBox.ScrollToCaret();
                        refs.StatsLabel.Text = $"发送: {_sendCount} | 接收: {_receiveCount}";
                    });
                }
            }
            catch (Exception ex)
            {
                this.Invoke((MethodInvoker)delegate {
                    var refs = GetControlReferences();
                    refs.ReceiveBox.SelectionColor = Color.Red;
                    refs.ReceiveBox.AppendText($"[接收错误] {ex.Message}\n");
                    refs.ReceiveBox.SelectionColor = Color.Lime;
                });
            }
        }
        private ControlReference GetControlReferences()
        {
            foreach (Control ctrl in this.Controls)
            {
                if (ctrl is ControlReference refs)
                {
                    return refs;
                }
            }
            return null;
        }

        // 用于保存控件引用的嵌套类
        private class ControlReference : Control
        {
            public Label StatusLabel { get; }
            public Label StatsLabel { get; }
            public RichTextBox ReceiveBox { get; }

            public ControlReference(Label statusLabel, Label statsLabel, RichTextBox receiveBox)
            {
                StatusLabel = statusLabel;
                StatsLabel = statsLabel;
                ReceiveBox = receiveBox;
            }
        }


        private void MainForm_FormClosing(object sender, FormClosingEventArgs e)
        {
            _isRunning = false;
            _isSending = false;

            if (_serialPort != null && _serialPort.IsOpen)
            {
                _serialPort.Close();
            }
        }
        //private void MainForm_FormClosing(object sender, FormClosingEventArgs e)
        //{
        //    if (MessageBox.Show("确定要退出吗?", "确认",
        //                        MessageBoxButtons.YesNo) == DialogResult.No)
        //    {
        //        e.Cancel = true; // 取消关闭
        //    }
        //}
        private void textBox1_TextChanged(object sender, EventArgs e)
        {

        }

        private void button1_Click(object sender, EventArgs e)
        {
            InitializeSerialPort();
        }


        private void SendButton_Click(object sender, EventArgs e)
        {
            InitializeSerialPort();
            if (!_isSending)
            {
                // 启动发送
                _isSending = true;
                ((Button)sender).Text = "停止发送";
                ((Button)sender).BackColor = Color.FromArgb(200, 0, 0);

                _sendThread = new Thread(SendData);
                _sendThread.IsBackground = true;
                _sendThread.Start();

                UpdateStatus("正在发送数据...", Color.LightGreen);
            }
            else
            {
                // 停止发送
                _isSending = false;
                ((Button)sender).Text = "启动发送";
                ((Button)sender).BackColor = Color.FromArgb(0, 122, 204);

                UpdateStatus("发送已停止", Color.LightCoral);
            }
        }
        private void SendData()
        {
            while (_isSending && _isRunning)
            {
                try
                {
                    _serialPort.Write("A");
                    _sendCount++;

                    // 更新UI
                    this.Invoke((MethodInvoker)delegate {
                        var refs = GetControlReferences();
                        refs.StatsLabel.Text = $"发送: {_sendCount} | 接收: {_receiveCount}";
                        refs.ReceiveBox.SelectionColor = Color.Cyan;
                        refs.ReceiveBox.AppendText($"[发送] A ({DateTime.Now:HH:mm:ss})\n");
                        refs.ReceiveBox.SelectionColor = Color.Lime;
                        refs.ReceiveBox.ScrollToCaret();
                    });
                }
                catch (Exception ex)
                {
                    this.Invoke((MethodInvoker)delegate {
                        var refs = GetControlReferences();
                        refs.ReceiveBox.SelectionColor = Color.Red;
                        refs.ReceiveBox.AppendText($"[发送错误] {ex.Message}\n");
                        refs.ReceiveBox.SelectionColor = Color.Lime;
                        refs.ReceiveBox.ScrollToCaret();
                    });
                }

                Thread.Sleep(1000); // 每秒发送一次
            }
        }

        private void ClearButton_Click(object sender, EventArgs e)
        {
            var refs = GetControlReferences();
            refs.ReceiveBox.Clear();
        }

    }


    internal class ControlReference : Control
    {
        private Label statusLabel;
        private Label statsLabel;
        private RichTextBox receiveBox;

        public ControlReference(Label statusLabel, Label statsLabel, RichTextBox receiveBox)
        {
            this.statusLabel = statusLabel;
            this.statsLabel = statsLabel;
            this.receiveBox = receiveBox;
        }
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

iCxhust

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值