WinForm串口通讯

目录

一 设计原型

二 源码


一 设计原型

二 源码

using System.IO.Ports;
using System.Text;

namespace 串口通讯
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        SerialPort serialPort = new SerialPort();


        private void open_Click(object sender, EventArgs e)
        {
            try
            {
                if (!serialPort.IsOpen)
                {
                    serialPort.Open();
                    serialPort.DataReceived += SerialPort_DataReceived;
                }
            }
            catch (Exception ex)
            {
                log.Text = ex.Message;
            }
        }

        private void read_Click(object sender, EventArgs e)
        {

        }

        private void write_Click(object sender, EventArgs e)
        {
            serialPort.Write(log.Text);
        }


        private void Form1_Load(object sender, EventArgs e)
        {
            //导入一些基础参数
            List<string> ports = SerialPort.GetPortNames().ToList();
            foreach (var item in ports)
            {
                port.Items.Add(item);
            }

            List<int> baus = new List<int> { 9600, 115200 };
            foreach (var item in baus)
            {
                bau.Items.Add(item);
            }

            List<int> databits = new List<int> { 6, 7, 8 };
            foreach (var item in databits)
            {
                databit.Items.Add(item);
            }

            List<string> cks = new List<string> { "None" };
            foreach (var item in cks)
            {
                check.Items.Add(item);
            }

            List<string> stops = new List<string> { "One" };
            foreach (var item in stops)
            {
                stop.Items.Add(item);
            }

            try
            {
                serialPort.PortName = port.Text;
                serialPort.BaudRate = int.Parse(bau.Text);
                serialPort.Parity = Parity.None;
                serialPort.DataBits = int.Parse(databit.Text);
                serialPort.StopBits = StopBits.One;

            }
            catch (Exception ex)
            {
                log.Text = ex.Message;
            }


        }

        private void SerialPort_DataReceived(object sender, SerialDataReceivedEventArgs e)
        {
            byte[] bytes = new byte[1024];
            try
            {
                serialPort.Read(bytes, 0, bytes.Length);
                string data = Encoding.UTF8.GetString(bytes);
                this.Invoke(() =>
                {
                    log.Text = data;
                });
            }
            catch (Exception ex)
            {
                log.Text = ex.Message;
            }
        }
    }
}

设计器自动生成代码:

namespace 串口通讯
{
    partial class Form1
    {
        /// <summary>
        ///  Required designer variable.
        /// </summary>
        private System.ComponentModel.IContainer components = null;

        /// <summary>
        ///  Clean up any resources being used.
        /// </summary>
        /// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
        protected override void Dispose(bool disposing)
        {
            if (disposing && (components != null))
            {
                components.Dispose();
            }
            base.Dispose(disposing);
        }

        #region Windows Form Designer generated code

        /// <summary>
        ///  Required method for Designer support - do not modify
        ///  the contents of this method with the code editor.
        /// </summary>
        private void InitializeComponent()
        {
            label1 = new Label();
            label2 = new Label();
            label3 = new Label();
            label4 = new Label();
            label5 = new Label();
            port = new ComboBox();
            bau = new ComboBox();
            databit = new ComboBox();
            check = new ComboBox();
            stop = new ComboBox();
            open = new Button();
            write = new Button();
            log = new RichTextBox();
            SuspendLayout();
            // 
            // label1
            // 
            label1.AutoSize = true;
            label1.Location = new Point(26, 14);
            label1.Name = "label1";
            label1.Size = new Size(39, 20);
            label1.TabIndex = 0;
            label1.Text = "端口";
            // 
            // label2
            // 
            label2.AutoSize = true;
            label2.Location = new Point(26, 54);
            label2.Name = "label2";
            label2.Size = new Size(54, 20);
            label2.TabIndex = 1;
            label2.Text = "波特率";
            // 
            // label3
            // 
            label3.AutoSize = true;
            label3.Location = new Point(26, 174);
            label3.Name = "label3";
            label3.Size = new Size(54, 20);
            label3.TabIndex = 2;
            label3.Text = "停止位";
            // 
            // label4
            // 
            label4.AutoSize = true;
            label4.Location = new Point(26, 134);
            label4.Name = "label4";
            label4.Size = new Size(54, 20);
            label4.TabIndex = 3;
            label4.Text = "校验位";
            // 
            // label5
            // 
            label5.AutoSize = true;
            label5.Location = new Point(26, 94);
            label5.Name = "label5";
            label5.Size = new Size(54, 20);
            label5.TabIndex = 4;
            label5.Text = "数据位";
            // 
            // port
            // 
            port.FormattingEnabled = true;
            port.Location = new Point(105, 11);
            port.Name = "port";
            port.Size = new Size(151, 28);
            port.TabIndex = 5;
            // 
            // bau
            // 
            bau.FormattingEnabled = true;
            bau.Location = new Point(105, 51);
            bau.Name = "bau";
            bau.Size = new Size(151, 28);
            bau.TabIndex = 6;
            // 
            // databit
            // 
            databit.FormattingEnabled = true;
            databit.Location = new Point(106, 91);
            databit.Name = "databit";
            databit.Size = new Size(151, 28);
            databit.TabIndex = 7;
            // 
            // check
            // 
            check.FormattingEnabled = true;
            check.Location = new Point(105, 134);
            check.Name = "check";
            check.Size = new Size(151, 28);
            check.TabIndex = 8;
            // 
            // stop
            // 
            stop.FormattingEnabled = true;
            stop.Location = new Point(105, 174);
            stop.Name = "stop";
            stop.Size = new Size(151, 28);
            stop.TabIndex = 9;
            // 
            // open
            // 
            open.Location = new Point(26, 214);
            open.Name = "open";
            open.Size = new Size(230, 29);
            open.TabIndex = 10;
            open.Text = "打开串口";
            open.UseVisualStyleBackColor = true;
            open.Click += open_Click;
            // 
            // write
            // 
            write.Location = new Point(26, 378);
            write.Name = "write";
            write.Size = new Size(231, 29);
            write.TabIndex = 12;
            write.Text = "写入数据";
            write.UseVisualStyleBackColor = true;
            write.Click += write_Click;
            // 
            // log
            // 
            log.Location = new Point(26, 253);
            log.Name = "log";
            log.Size = new Size(230, 115);
            log.TabIndex = 13;
            log.Text = "";
            // 
            // Form1
            // 
            AutoScaleDimensions = new SizeF(9F, 20F);
            AutoScaleMode = AutoScaleMode.Font;
            ClientSize = new Size(295, 419);
            Controls.Add(log);
            Controls.Add(write);
            Controls.Add(open);
            Controls.Add(stop);
            Controls.Add(check);
            Controls.Add(databit);
            Controls.Add(bau);
            Controls.Add(port);
            Controls.Add(label5);
            Controls.Add(label4);
            Controls.Add(label3);
            Controls.Add(label2);
            Controls.Add(label1);
            MaximizeBox = false;
            Name = "Form1";
            Text = "串口通讯";
            Load += Form1_Load;
            ResumeLayout(false);
            PerformLayout();
        }

        #endregion

        private Label label1;
        private Label label2;
        private Label label3;
        private Label label4;
        private Label label5;
        private ComboBox port;
        private ComboBox bau;
        private ComboBox databit;
        private ComboBox check;
        private ComboBox stop;
        private Button open;
        private Button write;
        private RichTextBox log;
    }
}

WinForm串口通信是通过在WinForm应用程序中建立串口通讯来实现。首先,需要检查电脑上是否有可用的串口。然后,根据需要修改串口的相关信息,如波特率、数据位、校验位和停止位等。在WinForm窗体中,可以显示串口接收到的实时数据。 例如,可以给打开串口按钮绑定打开串口事件。在事件处理程序中,需要进行串口配置,包括PortName(串口名称)、BaudRate(波特率)、DataBits(数据位)、Parity(校验位)和StopBits(停止位)等五个参数。其中,波特率是以字符串形式呈现的,需要使用Convert.ToInt32()方法将其转换为整数类型。 WinForm串口通信的具体步骤可以分为以下几个方法或步骤: 1. 创建虚拟串口 2. 创建WinForm应用程序 3. 绘制WinForm窗体 4. 进行属性初始化 5. 加载界面事件与初始化控件 6. 设置波特率选择事件 7. 检测可用串口 8. 进行串口设置 9. 打开或关闭串口 10. 发送和接收数据 11. 编写完整的代码 12. 进行测试并查看结果 13. 可以下载Demo来进行参考和学习。<span class="em">1</span><span class="em">2</span><span class="em">3</span> #### 引用[.reference_title] - *1* [Winform串口通讯](https://download.csdn.net/download/me683547/87793361)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v93^chatsearchT3_1"}}] [.reference_item style="max-width: 33.333333333333336%"] - *2* [1小时搞定C# winForm串口通信](https://blog.csdn.net/niuyong_10086/article/details/108882823)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v93^chatsearchT3_1"}}] [.reference_item style="max-width: 33.333333333333336%"] - *3* [C# WinForm下利用虚拟串口工具进行串口通信](https://blog.csdn.net/lwkliuwenkang/article/details/130357331)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v93^chatsearchT3_1"}}] [.reference_item style="max-width: 33.333333333333336%"] [ .reference_list ]
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值