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;
    }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

code_shenbing

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

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

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

打赏作者

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

抵扣说明:

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

余额充值