C# 串口助手小应用

C# 串口助手小应用

一、简述

        记--使用C#+VS2010编写简单的串口助手小应用。(测试版本)

        工程打包:链接: https://pan.baidu.com/s/1T9ZA8jnsjXDhNLuL1ezGdg 提取码: 6usr 

二、效果

        1、使用HC-06蓝牙模块进行测试(给蓝牙模块发送AT指令,它会回复OK)

              

        2、使用Proteus仿真+虚拟串口软件  进行测试

            (protues仿真STC51单片机,单片机收到之后回复:I received.。如果单片机收到的是'1'则点亮LED灯,否则熄灭LED灯)

             

三、工程结构

                     

四、源文件

        Program.cs文件

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.IO.Ports;

namespace 串口助手
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        //创建串口操作对象
        SerialPort serialPort = new System.IO.Ports.SerialPort();
        uint sendCount = 0;//记录发送的数目
        uint recvCount = 0;//记录接收到的数目
        System.Timers.Timer timer1 = new System.Timers.Timer();//定时器,用来实现自动发送
    
        //清空接收区按钮 响应函数
        private void button2_Click(object sender, EventArgs e)
        {
            txtbRecv.Text = "";
        }

        //窗体加载执行的函数
        private void Form1_Load(object sender, EventArgs e)
        {
            //添加端口列表
            cmbPort.Items.AddRange(System.IO.Ports.SerialPort.GetPortNames());

            //添加波特率列表
            int i;
            for (i = 300; i <= 38400; i = i*2)
            {
                cmbBaud.Items.Add(i.ToString());  
            }
            string[] baud = { "43000", "56000", "57600", "115200", "128000", "230400", "256000", "460800" };
            cmbBaud.Items.AddRange(baud);

            //添加检验方式列表
            string[] check = { "None", "Odd(奇校验)", "Even(偶校验)", "Mark校验", "Space校验" };
            cmbCheck.Items.AddRange(check);

            //添加数据位列表
            string[] data = { "5", "6", "7", "8"};
            cmbData.Items.AddRange(data);

            //添加停止位列表
            string[] stop = { "1", "1.5", "2" };
            cmbStop.Items.AddRange(stop);


            //设置默认值
            if (cmbPort.Items.Count > 0)//如果端口个数大于0
            {
                cmbPort.SelectedIndex = 0;//默认选中第一个端口
            }
            cmbBaud.Text = "9600";
            cmbData.Text = "8";
            cmbCheck.Text = "None";
            cmbStop.Text = "1";

            radRecvText.Checked = true;//接收区默认以文本方式显示
            radSendText.Checked = true;//发送区默认以文本方式发送
            numericTime.Controls[1].Text = "1000";//设置初始值为1000毫秒=1秒
            numericTime.Maximum = 999999;//设置最大值

            serialPort.DataReceived += new SerialDataReceivedEventHandler(serialRecvData);//注册串口数据接收事件,就是当串口就收到数据之后会调用serialRecvData函数
            timer1.Elapsed += new System.Timers.ElapsedEventHandler(timer1_timeout);//到达时间的时候执行事件;
            //timer1.Enabled = false;//不使能定时器
            //timer1.AutoReset = true;//设置是执行一次(false)还是一直执行(true);
            
        }

        //当串口就收到数据之后会 调用的函数
        private void serialRecvData(object sender, SerialDataReceivedEventArgs e)
        {
            try
            {
                string recvContent = null;//用来存放接收到的内容
                
                byte[] data = new byte[serialPort.BytesToRead];//申请存放数据的缓冲区
                serialPort.Read(data, 0, data.Length);//读取数据到data中
                
                if (chbRecvTime.Checked)//如果勾选 显示接收数据时间
                {
                    recvContent = ("[" + System.DateTime.Now.ToShortTimeString() + "] ");//显示当前时间
                }

                if (radRecvHex.Checked)//选择以16进制方式显示
                {
                    StringBuilder recvData = new StringBuilder();//用来存放接收到的数据的字符串形式   
                    for (int i = 0; i < data.Length; i++)
                    {
                        recvData.Append(data[i].ToString("X2") + ' ');//转为16进制形式的字符串,并以空格隔开
                    }
                    recvContent += recvData.ToString().ToUpper();//将接收到的内容追加到接收区
                    recvCount += (uint)data.Length / 2;//将收到的数目加到总数目中(十六进制2个位置表示一个数据,空格不计)
                }
                else //选择以文本方式显示
                {
                    recvContent += new ASCIIEncoding().GetString(data);//将接收到的内容追加到接收区
                    recvCount += (uint)data.Length;//将收到的数目加到总数目中
                }

                //使用Invoke访问主线程创建的控件
                this.Invoke((EventHandler)(delegate
                {
                    txtbRecv.AppendText(recvContent);
                    lblRecvCount.Text = "接收:" + recvCount + " 字节";//将接收到的总字节数显示到下方的状态栏中
                }));

                
            }
            catch {}
        }

        //清空发送区 按钮的响应函数
        private void btnClrSend_Click(object sender, EventArgs e)
        {
            txtbSend.Text = "";
        }

        //打开串口 按钮点击响应函数
        private void btnOpenSerial_Click(object sender, EventArgs e)
        {
            if (cmbPort.Text.Equals(""))//如果选中项为空
            {
                MessageBox.Show("请选择端口!");
                return;
            }

            try
            {
                if (serialPort.IsOpen)//如果串口已经打开,就关闭串口
                {
                    serialPort.Close();//关闭串口
                    timer1.Stop();     //停止定时器
                    lblSerialStat.Text = "串口已关闭";//在底部状态栏显示 "串口已关闭"
                    lblSerialStat.ForeColor = Color.FromArgb(0, 0, 0);//设置字体颜色为黑色
                    btnOpenSerial.Text = "打开串口";//将按钮文本显示为 “打开串口”
                    btnOpenSerial.BackColor = Color.FromArgb(221, 221, 221);//将按钮的背景色设置为 初始按钮的颜色

                }
                else //串口处于关闭状态, 就打开串口
                {
                    serialPort.PortName = cmbPort.Text;//设置端口
                    serialPort.BaudRate = Convert.ToInt32(cmbBaud.Text);//设置波特率
                    serialPort.DataBits = Convert.ToInt16(cmbData.Text);//设置数据位

                    //设置检验方式
                    if (cmbCheck.Text.Equals("None"))
                        serialPort.Parity = System.IO.Ports.Parity.None;
                    else if (cmbCheck.Text.Equals("Odd(奇校验)"))
                        serialPort.Parity = System.IO.Ports.Parity.Odd;
                    else if (cmbCheck.Text.Equals("Even(偶校验)"))
                        serialPort.Parity = System.IO.Ports.Parity.Even;
                    else if (cmbCheck.Text.Equals("Mark校验"))
                        serialPort.Parity = System.IO.Ports.Parity.Mark;
                    else if (cmbCheck.Text.Equals("Space校验"))
                        serialPort.Parity = System.IO.Ports.Parity.Space;


                    //设置停止位
                    if (cmbStop.Text.Equals("1"))
                        serialPort.StopBits = System.IO.Ports.StopBits.One;
                    else if (cmbStop.Text.Equals("1.5"))
                        serialPort.StopBits = System.IO.Ports.StopBits.OnePointFive;
                    else if (cmbStop.Text.Equals("2"))
                        serialPort.StopBits = System.IO.Ports.StopBits.Two;

                    //打开串口
                    serialPort.Open();
                    lblSerialStat.Text = "串口已打开";//在底部状态栏显示 "串口已打开"
                    lblSerialStat.ForeColor = Color.Green;//设置字体颜色为绿色
                    btnOpenSerial.Text = "关闭串口";//设置按钮的显示文本为 “关闭串口”
                    btnOpenSerial.BackColor = Color.ForestGreen;//设置按钮背景色为 树绿色
                }
            }
            catch //简单的处理异常
            {
                afterException();
                MessageBox.Show("   打开串口失败!\n串口不存在或串口已经被打开!");
            }
        }

        //出现异常后执行的函数
        private void afterException()
        {
            //重新创建串口操作对象
            serialPort = new System.IO.Ports.SerialPort();
            timer1.Stop();     //停止定时器

            //使用Invoke访问主线程创建的控件(代理(也即委托)的方式来访问)
            this.Invoke((EventHandler)(delegate
            {
                lblSerialStat.Text = "串口已关闭";//在底部状态栏显示 "串口已关闭"
                lblSerialStat.ForeColor = Color.FromArgb(0, 0, 0);//设置字体颜色为黑色
                btnOpenSerial.Text = "打开串口";//将按钮文本显示为 “打开串口”
                btnOpenSerial.BackColor = Color.FromArgb(221, 221, 221);//将按钮的背景色设置为 初始按钮的颜色
            }));

        }

        //发送 按钮点击 响应函数
        private void btnSend_Click(object sender, EventArgs e)
        {
            try
            {
                //要发送的内容
                string content = txtbSend.Text.Trim();//txtbSend.Text.Trim()获取发送区的内容,Trim():去掉前后空格,然后转为ASCII码字节数组
                if (content.Equals(""))//如果发送内容为空,直接返回
                {
                    return;
                }
                if (serialPort.IsOpen)//在串口打开的状态下才发送
                {
                    byte[] sendData = null;
                    try
                    {
                        if (radSendText.Checked)//选择的是文本方式发送
                        {
                            sendData = Encoding.ASCII.GetBytes(content);//将内容转为ASCII格式
                        }
                        else //选择的是16进制方式发送 
                        {
                            sendData = new byte[(content.Length + 1) / 2];//2个字符一组,加1操作是防止奇数情况漏掉一个
                            for (int i = 0; i < sendData.Length; i++)//将内容转为16进制格式
                            {
                                sendData[i] = Convert.ToByte(content.Substring(i * 2, 2).Replace(" ", ""), 16);//每两个字符转为16进制的格式,并将空格替换掉
                            }
                        }
                    }
                    catch //如果转换过程出现异常(出现不是十六进制字符的),直接返回
                    {
                        return;
                    }

                    try
                    {
                        serialPort.Write(sendData, 0, sendData.Length);//从串口发送数据

                        if (chbSendNewLine.Checked)//如果勾选自动发送新行
                        {
                            serialPort.WriteLine("");//发送新行
                            sendCount++;//发送的字符数+1

                        }
                    }
                    catch //如果发送数据时出现异常
                    {
                        afterException();
                    }

                    sendCount += (uint)sendData.Length;//记录发送的数目
                    lblSendCount.Text = "发送:" + sendCount + "字节";//将发送的字符数统计并显示到标签中。
                }
                else
                {
                    MessageBox.Show("请打开串口!");
                }
            }
            catch { }
        }

        //清空计数 按钮 点击响应函数
        private void btnClrCount_Click(object sender, EventArgs e)
        {
            lblSendCount.Text = "发送:0 字节";
            lblRecvCount.Text = "接收:0 字节";
            sendCount = 0;//清空发送总数目
            recvCount = 0;//清空接收总数目
        }

        //刷新端口 按钮点击响应函数
        private void btnRefresh_Click(object sender, EventArgs e)
        {
            try
            {
                if (serialPort.IsOpen)//如果串口已经打开,就不重新扫描
                {
                    return;
                }
                //清空原来的列表数据
                cmbPort.Items.Clear();
                //重新扫描端口,添加端口列表
                cmbPort.Items.AddRange(System.IO.Ports.SerialPort.GetPortNames());

                if (cmbPort.Items.Count > 0)//如果端口个数大于0
                {
                    cmbPort.SelectedIndex = 0;//默认选中第一个端口
                }
            }
            catch
            {
                afterException();
            }
        }

        //当自动发送的勾选框状态发生变化时 执行的函数
        private void chbAutoSend_CheckedChanged(object sender, EventArgs e)
        {
            try
            {
                if (!serialPort.IsOpen)//如果串口没有打开,就直接返回
                {
                    return;
                }

                if (chbAutoSend.Checked)//如果是勾选自动发送,
                {
                    timer1.Interval = Convert.ToInt32(numericTime.Controls[1].Text);//定时器赋初值
                    timer1.AutoReset = true;//自动重装初值
                    timer1.Start();     //启动定时器
                    lblSerialStat.Text = "串口已打开" + " 自动发送中...";//提示正在处于自动发送中
                }
                else //如果是取消勾选自动发送
                {
                    timer1.Stop();     //停止定时器
                    lblSerialStat.Text = "串口已打开";
                }
            }
            catch {}
        }

        //定时器到时 执行的函数
        private void timer1_timeout(object sender, EventArgs e)
        {
            //使用Invoke访问主线程创建的控件(代理(也即委托)的方式来访问)
            this.Invoke((EventHandler)(delegate
            {
                btnSend_Click(btnSend, new EventArgs());  //定时时间到,就执行 发送按钮的点击响应函数
            }));
           
        }

        //窗体关闭的时候执行的函数
        private void Form1_FormClosing(object sender, FormClosingEventArgs e)
        {
            try
            {
                if (serialPort.IsOpen)//如果窗体关闭时串口已经打开,那么就关闭串口
                {
                    serialPort.Close();//关闭串口
                }
            }
            catch { }
        }
    }
}

Form1.Designer.cs

namespace 串口助手
{
    partial class Form1
    {
        /// <summary>
        /// 必需的设计器变量。
        /// </summary>
        private System.ComponentModel.IContainer components = null;

        /// <summary>
        /// 清理所有正在使用的资源。
        /// </summary>
        /// <param name="disposing">如果应释放托管资源,为 true;否则为 false。</param>
        protected override void Dispose(bool disposing)
        {
            if (disposing && (components != null))
            {
                components.Dispose();
            }
            base.Dispose(disposing);
        }

        #region Windows 窗体设计器生成的代码

        /// <summary>
        /// 设计器支持所需的方法 - 不要
        /// 使用代码编辑器修改此方法的内容。
        /// </summary>
        private void InitializeComponent()
        {
            this.lblPort = new System.Windows.Forms.Label();
            this.lblBaud = new System.Windows.Forms.Label();
            this.lblData = new System.Windows.Forms.Label();
            this.lblCheck = new System.Windows.Forms.Label();
            this.lblStop = new System.Windows.Forms.Label();
            this.btnOpenSerial = new System.Windows.Forms.Button();
            this.radRecvText = new System.Windows.Forms.RadioButton();
            this.radRecvHex = new System.Windows.Forms.RadioButton();
            this.radSendHex = new System.Windows.Forms.RadioButton();
            this.radSendText = new System.Windows.Forms.RadioButton();
            this.chbRecvTime = new System.Windows.Forms.CheckBox();
            this.btnClrRecv = new System.Windows.Forms.Button();
            this.chbSendNewLine = new System.Windows.Forms.CheckBox();
            this.chbAutoSend = new System.Windows.Forms.CheckBox();
            this.lblSerialStat = new System.Windows.Forms.Label();
            this.lblRecvCount = new System.Windows.Forms.Label();
            this.lblSendCount = new System.Windows.Forms.Label();
            this.lblVertion = new System.Windows.Forms.Label();
            this.txtbSend = new System.Windows.Forms.TextBox();
            this.btnSend = new System.Windows.Forms.Button();
            this.btnClrCount = new System.Windows.Forms.Button();
            this.btnClrSend = new System.Windows.Forms.Button();
            this.cmbPort = new System.Windows.Forms.ComboBox();
            this.cmbBaud = new System.Windows.Forms.ComboBox();
            this.cmbData = new System.Windows.Forms.ComboBox();
            this.cmbCheck = new System.Windows.Forms.ComboBox();
            this.cmbStop = new System.Windows.Forms.ComboBox();
            this.numericTime = new System.Windows.Forms.NumericUpDown();
            this.label1 = new System.Windows.Forms.Label();
            this.btnRefresh = new System.Windows.Forms.Button();
            this.groupBoxSerialSettings = new System.Windows.Forms.GroupBox();
            this.groupBoxRecvArea = new System.Windows.Forms.GroupBox();
            this.txtbRecv = new System.Windows.Forms.TextBox();
            this.groupBoxRecvSettings = new System.Windows.Forms.GroupBox();
            this.groupBoxSendSettings = new System.Windows.Forms.GroupBox();
            this.groupBoxSendArea = new System.Windows.Forms.GroupBox();
            this.panelInfo = new System.Windows.Forms.Panel();
            ((System.ComponentModel.ISupportInitialize)(this.numericTime)).BeginInit();
            this.groupBoxSerialSettings.SuspendLayout();
            this.groupBoxRecvArea.SuspendLayout();
            this.groupBoxRecvSettings.SuspendLayout();
            this.groupBoxSendSettings.SuspendLayout();
            this.groupBoxSendArea.SuspendLayout();
            this.panelInfo.SuspendLayout();
            this.SuspendLayout();
            // 
            // lblPort
            // 
            this.lblPort.AutoSize = true;
            this.lblPort.Location = new System.Drawing.Point(12, 23);
            this.lblPort.Name = "lblPort";
            this.lblPort.Size = new System.Drawing.Size(41, 12);
            this.lblPort.TabIndex = 0;
            this.lblPort.Text = "端  口";
            // 
            // lblBaud
            // 
            this.lblBaud.AutoSize = true;
            this.lblBaud.Location = new System.Drawing.Point(12, 50);
            this.lblBaud.Name = "lblBaud";
            this.lblBaud.Size = new System.Drawing.Size(41, 12);
            this.lblBaud.TabIndex = 1;
            this.lblBaud.Text = "波特率";
            // 
            // lblData
            // 
            this.lblData.AutoSize = true;
            this.lblData.Location = new System.Drawing.Point(12, 81);
            this.lblData.Name = "lblData";
            this.lblData.Size = new System.Drawing.Size(41, 12);
            this.lblData.TabIndex = 2;
            this.lblData.Text = "数据位";
            // 
            // lblCheck
            // 
            this.lblCheck.AutoSize = true;
            this.lblCheck.Location = new System.Drawing.Point(12, 111);
            this.lblCheck.Name = "lblCheck";
            this.lblCheck.Size = new System.Drawing.Size(41, 12);
            this.lblCheck.TabIndex = 3;
            this.lblCheck.Text = "校验位";
            // 
            // lblStop
            // 
            this.lblStop.AutoSize = true;
            this.lblStop.Location = new System.Drawing.Point(12, 145);
            this.lblStop.Name = "lblStop";
            this.lblStop.Size = new System.Drawing.Size(41, 12);
            this.lblStop.TabIndex = 4;
            this.lblStop.Text = "停止位";
            // 
            // btnOpenSerial
            // 
            this.btnOpenSerial.Location = new System.Drawing.Point(14, 173);
            this.btnOpenSerial.Name = "btnOpenSerial";
            this.btnOpenSerial.Size = new System.Drawing.Size(139, 32);
            this.btnOpenSerial.TabIndex = 5;
            this.btnOpenSerial.Text = "打开串口";
            this.btnOpenSerial.UseVisualStyleBackColor = true;
            this.btnOpenSerial.Click += new System.EventHandler(this.btnOpenSerial_Click);
            // 
            // radRecvText
            // 
            this.radRecvText.AutoSize = true;
            this.radRecvText.Location = new System.Drawing.Point(11, 28);
            this.radRecvText.Name = "radRecvText";
            this.radRecvText.Size = new System.Drawing.Size(47, 16);
            this.radRecvText.TabIndex = 7;
            this.radRecvText.TabStop = true;
            this.radRecvText.Text = "文本";
            this.radRecvText.UseVisualStyleBackColor = true;
            // 
            // radRecvHex
            // 
            this.radRecvHex.AutoSize = true;
            this.radRecvHex.Location = new System.Drawing.Point(80, 28);
            this.radRecvHex.Name = "radRecvHex";
            this.radRecvHex.Size = new System.Drawing.Size(71, 16);
            this.radRecvHex.TabIndex = 8;
            this.radRecvHex.TabStop = true;
            this.radRecvHex.Text = "十六进制";
            this.radRecvHex.UseVisualStyleBackColor = true;
            // 
            // radSendHex
            // 
            this.radSendHex.AutoSize = true;
            this.radSendHex.Location = new System.Drawing.Point(83, 27);
            this.radSendHex.Name = "radSendHex";
            this.radSendHex.Size = new System.Drawing.Size(71, 16);
            this.radSendHex.TabIndex = 10;
            this.radSendHex.TabStop = true;
            this.radSendHex.Text = "十六进制";
            this.radSendHex.UseVisualStyleBackColor = true;
            // 
            // radSendText
            // 
            this.radSendText.AutoSize = true;
            this.radSendText.Location = new System.Drawing.Point(14, 27);
            this.radSendText.Name = "radSendText";
            this.radSendText.Size = new System.Drawing.Size(47, 16);
            this.radSendText.TabIndex = 9;
            this.radSendText.TabStop = true;
            this.radSendText.Text = "文本";
            this.radSendText.UseVisualStyleBackColor = true;
            // 
            // chbRecvTime
            // 
            this.chbRecvTime.AutoSize = true;
            this.chbRecvTime.Location = new System.Drawing.Point(11, 59);
            this.chbRecvTime.Name = "chbRecvTime";
            this.chbRecvTime.Size = new System.Drawing.Size(120, 16);
            this.chbRecvTime.TabIndex = 9;
            this.chbRecvTime.Text = "显示接收数据时间";
            this.chbRecvTime.UseVisualStyleBackColor = true;
            // 
            // btnClrRecv
            // 
            this.btnClrRecv.Location = new System.Drawing.Point(6, 81);
            this.btnClrRecv.Name = "btnClrRecv";
            this.btnClrRecv.Size = new System.Drawing.Size(140, 29);
            this.btnClrRecv.TabIndex = 10;
            this.btnClrRecv.Text = "清空接收区";
            this.btnClrRecv.UseVisualStyleBackColor = true;
            this.btnClrRecv.Click += new System.EventHandler(this.button2_Click);
            // 
            // chbSendNewLine
            // 
            this.chbSendNewLine.AutoSize = true;
            this.chbSendNewLine.Location = new System.Drawing.Point(14, 64);
            this.chbSendNewLine.Name = "chbSendNewLine";
            this.chbSendNewLine.Size = new System.Drawing.Size(72, 16);
            this.chbSendNewLine.TabIndex = 11;
            this.chbSendNewLine.Text = "发送新行";
            this.chbSendNewLine.UseVisualStyleBackColor = true;
            // 
            // chbAutoSend
            // 
            this.chbAutoSend.AutoSize = true;
            this.chbAutoSend.Location = new System.Drawing.Point(14, 87);
            this.chbAutoSend.Name = "chbAutoSend";
            this.chbAutoSend.Size = new System.Drawing.Size(72, 16);
            this.chbAutoSend.TabIndex = 12;
            this.chbAutoSend.Text = "自动发送";
            this.chbAutoSend.UseVisualStyleBackColor = true;
            this.chbAutoSend.CheckedChanged += new System.EventHandler(this.chbAutoSend_CheckedChanged);
            // 
            // lblSerialStat
            // 
            this.lblSerialStat.AutoSize = true;
            this.lblSerialStat.Location = new System.Drawing.Point(3, 7);
            this.lblSerialStat.Name = "lblSerialStat";
            this.lblSerialStat.Size = new System.Drawing.Size(65, 12);
            this.lblSerialStat.TabIndex = 0;
            this.lblSerialStat.Text = "串口已关闭";
            // 
            // lblRecvCount
            // 
            this.lblRecvCount.AutoSize = true;
            this.lblRecvCount.Location = new System.Drawing.Point(142, 7);
            this.lblRecvCount.Name = "lblRecvCount";
            this.lblRecvCount.Size = new System.Drawing.Size(71, 12);
            this.lblRecvCount.TabIndex = 1;
            this.lblRecvCount.Text = "接收:0 字节";
            // 
            // lblSendCount
            // 
            this.lblSendCount.AutoSize = true;
            this.lblSendCount.Location = new System.Drawing.Point(272, 7);
            this.lblSendCount.Name = "lblSendCount";
            this.lblSendCount.Size = new System.Drawing.Size(71, 12);
            this.lblSendCount.TabIndex = 2;
            this.lblSendCount.Text = "发送:0 字节";
            // 
            // lblVertion
            // 
            this.lblVertion.AutoSize = true;
            this.lblVertion.Location = new System.Drawing.Point(477, 7);
            this.lblVertion.Name = "lblVertion";
            this.lblVertion.Size = new System.Drawing.Size(59, 12);
            this.lblVertion.TabIndex = 3;
            this.lblVertion.Text = "版本:V1.0";
            // 
            // txtbSend
            // 
            this.txtbSend.Location = new System.Drawing.Point(3, 20);
            this.txtbSend.Multiline = true;
            this.txtbSend.Name = "txtbSend";
            this.txtbSend.ScrollBars = System.Windows.Forms.ScrollBars.Vertical;
            this.txtbSend.Size = new System.Drawing.Size(252, 115);
            this.txtbSend.TabIndex = 0;
            // 
            // btnSend
            // 
            this.btnSend.Location = new System.Drawing.Point(261, 35);
            this.btnSend.Name = "btnSend";
            this.btnSend.Size = new System.Drawing.Size(77, 31);
            this.btnSend.TabIndex = 1;
            this.btnSend.Text = "发送";
            this.btnSend.UseVisualStyleBackColor = true;
            this.btnSend.Click += new System.EventHandler(this.btnSend_Click);
            // 
            // btnClrCount
            // 
            this.btnClrCount.Location = new System.Drawing.Point(405, 1);
            this.btnClrCount.Name = "btnClrCount";
            this.btnClrCount.Size = new System.Drawing.Size(66, 23);
            this.btnClrCount.TabIndex = 1;
            this.btnClrCount.Text = "清空计数";
            this.btnClrCount.UseVisualStyleBackColor = true;
            this.btnClrCount.Click += new System.EventHandler(this.btnClrCount_Click);
            // 
            // btnClrSend
            // 
            this.btnClrSend.Location = new System.Drawing.Point(261, 92);
            this.btnClrSend.Name = "btnClrSend";
            this.btnClrSend.Size = new System.Drawing.Size(77, 31);
            this.btnClrSend.TabIndex = 2;
            this.btnClrSend.Text = "清空发送区";
            this.btnClrSend.UseVisualStyleBackColor = true;
            this.btnClrSend.Click += new System.EventHandler(this.btnClrSend_Click);
            // 
            // cmbPort
            // 
            this.cmbPort.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList;
            this.cmbPort.FormattingEnabled = true;
            this.cmbPort.Location = new System.Drawing.Point(61, 15);
            this.cmbPort.Name = "cmbPort";
            this.cmbPort.Size = new System.Drawing.Size(71, 20);
            this.cmbPort.TabIndex = 6;
            // 
            // cmbBaud
            // 
            this.cmbBaud.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList;
            this.cmbBaud.FormattingEnabled = true;
            this.cmbBaud.Location = new System.Drawing.Point(59, 47);
            this.cmbBaud.Name = "cmbBaud";
            this.cmbBaud.Size = new System.Drawing.Size(73, 20);
            this.cmbBaud.TabIndex = 7;
            // 
            // cmbData
            // 
            this.cmbData.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList;
            this.cmbData.FormattingEnabled = true;
            this.cmbData.Location = new System.Drawing.Point(59, 78);
            this.cmbData.Name = "cmbData";
            this.cmbData.Size = new System.Drawing.Size(73, 20);
            this.cmbData.TabIndex = 8;
            // 
            // cmbCheck
            // 
            this.cmbCheck.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList;
            this.cmbCheck.FormattingEnabled = true;
            this.cmbCheck.Location = new System.Drawing.Point(59, 111);
            this.cmbCheck.Name = "cmbCheck";
            this.cmbCheck.Size = new System.Drawing.Size(73, 20);
            this.cmbCheck.TabIndex = 9;
            // 
            // cmbStop
            // 
            this.cmbStop.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList;
            this.cmbStop.FormattingEnabled = true;
            this.cmbStop.Location = new System.Drawing.Point(59, 142);
            this.cmbStop.Name = "cmbStop";
            this.cmbStop.Size = new System.Drawing.Size(73, 20);
            this.cmbStop.TabIndex = 10;
            // 
            // numericTime
            // 
            this.numericTime.Location = new System.Drawing.Point(83, 82);
            this.numericTime.Maximum = new decimal(new int[] {
            999999,
            0,
            0,
            0});
            this.numericTime.Name = "numericTime";
            this.numericTime.Size = new System.Drawing.Size(55, 21);
            this.numericTime.TabIndex = 13;
            // 
            // label1
            // 
            this.label1.AutoSize = true;
            this.label1.Location = new System.Drawing.Point(144, 87);
            this.label1.Name = "label1";
            this.label1.Size = new System.Drawing.Size(29, 12);
            this.label1.TabIndex = 14;
            this.label1.Text = "毫秒";
            // 
            // btnRefresh
            // 
            this.btnRefresh.Font = new System.Drawing.Font("宋体", 9F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(134)));
            this.btnRefresh.Location = new System.Drawing.Point(135, 13);
            this.btnRefresh.Margin = new System.Windows.Forms.Padding(0);
            this.btnRefresh.Name = "btnRefresh";
            this.btnRefresh.Size = new System.Drawing.Size(42, 22);
            this.btnRefresh.TabIndex = 11;
            this.btnRefresh.Text = "刷新";
            this.btnRefresh.UseVisualStyleBackColor = true;
            this.btnRefresh.Click += new System.EventHandler(this.btnRefresh_Click);
            // 
            // groupBoxSerialSettings
            // 
            this.groupBoxSerialSettings.Controls.Add(this.btnRefresh);
            this.groupBoxSerialSettings.Controls.Add(this.cmbCheck);
            this.groupBoxSerialSettings.Controls.Add(this.cmbStop);
            this.groupBoxSerialSettings.Controls.Add(this.lblPort);
            this.groupBoxSerialSettings.Controls.Add(this.lblBaud);
            this.groupBoxSerialSettings.Controls.Add(this.cmbData);
            this.groupBoxSerialSettings.Controls.Add(this.lblData);
            this.groupBoxSerialSettings.Controls.Add(this.cmbBaud);
            this.groupBoxSerialSettings.Controls.Add(this.lblStop);
            this.groupBoxSerialSettings.Controls.Add(this.cmbPort);
            this.groupBoxSerialSettings.Controls.Add(this.lblCheck);
            this.groupBoxSerialSettings.Controls.Add(this.btnOpenSerial);
            this.groupBoxSerialSettings.Location = new System.Drawing.Point(1, 5);
            this.groupBoxSerialSettings.Name = "groupBoxSerialSettings";
            this.groupBoxSerialSettings.Size = new System.Drawing.Size(180, 217);
            this.groupBoxSerialSettings.TabIndex = 1;
            this.groupBoxSerialSettings.TabStop = false;
            this.groupBoxSerialSettings.Text = "串口设置";
            // 
            // groupBoxRecvArea
            // 
            this.groupBoxRecvArea.Controls.Add(this.txtbRecv);
            this.groupBoxRecvArea.Location = new System.Drawing.Point(187, 12);
            this.groupBoxRecvArea.Name = "groupBoxRecvArea";
            this.groupBoxRecvArea.Size = new System.Drawing.Size(350, 311);
            this.groupBoxRecvArea.TabIndex = 1;
            this.groupBoxRecvArea.TabStop = false;
            this.groupBoxRecvArea.Text = "接收区";
            // 
            // txtbRecv
            // 
            this.txtbRecv.Location = new System.Drawing.Point(3, 17);
            this.txtbRecv.Margin = new System.Windows.Forms.Padding(0);
            this.txtbRecv.Multiline = true;
            this.txtbRecv.Name = "txtbRecv";
            this.txtbRecv.ScrollBars = System.Windows.Forms.ScrollBars.Vertical;
            this.txtbRecv.Size = new System.Drawing.Size(344, 286);
            this.txtbRecv.TabIndex = 0;
            // 
            // groupBoxRecvSettings
            // 
            this.groupBoxRecvSettings.Controls.Add(this.btnClrRecv);
            this.groupBoxRecvSettings.Controls.Add(this.chbRecvTime);
            this.groupBoxRecvSettings.Controls.Add(this.radRecvText);
            this.groupBoxRecvSettings.Controls.Add(this.radRecvHex);
            this.groupBoxRecvSettings.Location = new System.Drawing.Point(4, 228);
            this.groupBoxRecvSettings.Name = "groupBoxRecvSettings";
            this.groupBoxRecvSettings.Size = new System.Drawing.Size(180, 118);
            this.groupBoxRecvSettings.TabIndex = 1;
            this.groupBoxRecvSettings.TabStop = false;
            this.groupBoxRecvSettings.Text = "接收区设置";
            // 
            // groupBoxSendSettings
            // 
            this.groupBoxSendSettings.Controls.Add(this.label1);
            this.groupBoxSendSettings.Controls.Add(this.numericTime);
            this.groupBoxSendSettings.Controls.Add(this.radSendText);
            this.groupBoxSendSettings.Controls.Add(this.chbAutoSend);
            this.groupBoxSendSettings.Controls.Add(this.radSendHex);
            this.groupBoxSendSettings.Controls.Add(this.chbSendNewLine);
            this.groupBoxSendSettings.Location = new System.Drawing.Point(1, 352);
            this.groupBoxSendSettings.Name = "groupBoxSendSettings";
            this.groupBoxSendSettings.Size = new System.Drawing.Size(180, 118);
            this.groupBoxSendSettings.TabIndex = 1;
            this.groupBoxSendSettings.TabStop = false;
            this.groupBoxSendSettings.Text = "发送区设置";
            // 
            // groupBoxSendArea
            // 
            this.groupBoxSendArea.Controls.Add(this.btnClrSend);
            this.groupBoxSendArea.Controls.Add(this.btnSend);
            this.groupBoxSendArea.Controls.Add(this.txtbSend);
            this.groupBoxSendArea.Location = new System.Drawing.Point(187, 329);
            this.groupBoxSendArea.Name = "groupBoxSendArea";
            this.groupBoxSendArea.Size = new System.Drawing.Size(347, 141);
            this.groupBoxSendArea.TabIndex = 1;
            this.groupBoxSendArea.TabStop = false;
            this.groupBoxSendArea.Text = "发送区";
            // 
            // panelInfo
            // 
            this.panelInfo.Controls.Add(this.btnClrCount);
            this.panelInfo.Controls.Add(this.lblVertion);
            this.panelInfo.Controls.Add(this.lblSendCount);
            this.panelInfo.Controls.Add(this.lblRecvCount);
            this.panelInfo.Controls.Add(this.lblSerialStat);
            this.panelInfo.Location = new System.Drawing.Point(1, 473);
            this.panelInfo.Margin = new System.Windows.Forms.Padding(0);
            this.panelInfo.Name = "panelInfo";
            this.panelInfo.Size = new System.Drawing.Size(536, 29);
            this.panelInfo.TabIndex = 1;
            // 
            // Form1
            // 
            this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 12F);
            this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
            this.ClientSize = new System.Drawing.Size(538, 498);
            this.Controls.Add(this.groupBoxSendArea);
            this.Controls.Add(this.groupBoxSendSettings);
            this.Controls.Add(this.groupBoxRecvSettings);
            this.Controls.Add(this.groupBoxRecvArea);
            this.Controls.Add(this.groupBoxSerialSettings);
            this.Controls.Add(this.panelInfo);
            this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.FixedDialog;
            this.Name = "Form1";
            this.Text = "串口助手";
            this.FormClosing += new System.Windows.Forms.FormClosingEventHandler(this.Form1_FormClosing);
            this.Load += new System.EventHandler(this.Form1_Load);
            ((System.ComponentModel.ISupportInitialize)(this.numericTime)).EndInit();
            this.groupBoxSerialSettings.ResumeLayout(false);
            this.groupBoxSerialSettings.PerformLayout();
            this.groupBoxRecvArea.ResumeLayout(false);
            this.groupBoxRecvArea.PerformLayout();
            this.groupBoxRecvSettings.ResumeLayout(false);
            this.groupBoxRecvSettings.PerformLayout();
            this.groupBoxSendSettings.ResumeLayout(false);
            this.groupBoxSendSettings.PerformLayout();
            this.groupBoxSendArea.ResumeLayout(false);
            this.groupBoxSendArea.PerformLayout();
            this.panelInfo.ResumeLayout(false);
            this.panelInfo.PerformLayout();
            this.ResumeLayout(false);

        }

        #endregion

        private System.Windows.Forms.Button btnOpenSerial;
        private System.Windows.Forms.Label lblCheck;
        private System.Windows.Forms.Label lblStop;
        private System.Windows.Forms.Label lblData;
        private System.Windows.Forms.Label lblBaud;
        private System.Windows.Forms.Label lblPort;
        private System.Windows.Forms.Button btnClrRecv;
        private System.Windows.Forms.CheckBox chbRecvTime;
        private System.Windows.Forms.RadioButton radRecvHex;
        private System.Windows.Forms.RadioButton radRecvText;
        private System.Windows.Forms.RadioButton radSendHex;
        private System.Windows.Forms.RadioButton radSendText;
        private System.Windows.Forms.Button btnClrCount;
        private System.Windows.Forms.Label lblVertion;
        private System.Windows.Forms.Label lblSendCount;
        private System.Windows.Forms.Label lblRecvCount;
        private System.Windows.Forms.Label lblSerialStat;
        private System.Windows.Forms.CheckBox chbAutoSend;
        private System.Windows.Forms.CheckBox chbSendNewLine;
        private System.Windows.Forms.Button btnClrSend;
        private System.Windows.Forms.Button btnSend;
        private System.Windows.Forms.TextBox txtbSend;
        private System.Windows.Forms.ComboBox cmbStop;
        private System.Windows.Forms.ComboBox cmbCheck;
        private System.Windows.Forms.ComboBox cmbData;
        private System.Windows.Forms.ComboBox cmbBaud;
        private System.Windows.Forms.ComboBox cmbPort;
        private System.Windows.Forms.NumericUpDown numericTime;
        private System.Windows.Forms.Label label1;
        private System.Windows.Forms.Button btnRefresh;
        private System.Windows.Forms.GroupBox groupBoxSerialSettings;
        private System.Windows.Forms.GroupBox groupBoxRecvArea;
        private System.Windows.Forms.TextBox txtbRecv;
        private System.Windows.Forms.GroupBox groupBoxRecvSettings;
        private System.Windows.Forms.GroupBox groupBoxSendSettings;
        private System.Windows.Forms.GroupBox groupBoxSendArea;
        private System.Windows.Forms.Panel panelInfo;
    }
}

五、总结

5.1 主要函数操作

//获取串口操作对象:
SerialPort serialPort = new System.IO.Ports.SerialPort();(注:using System.IO.Ports;)

//设置串口属性:
serialPort.PortName = cmbPort.Text;//设置端口
serialPort.BaudRate = Convert.ToInt32(cmbBaud.Text);//设置波特率
serialPort.DataBits = Convert.ToInt16(cmbData.Text);//设置数据位
serialPort.Parity = System.IO.Ports.Parity.None;//设置检验方式
serialPort.StopBits = System.IO.Ports.StopBits.One;//设置停止位
serialPort.Open();//打开串口
serialPort.Close();//关闭串口

serialPort.DataReceived += new SerialDataReceivedEventHandler(serialRecvData);//注册串口数据接收事件,就是当串口就收到数据之后会调用serialRecvData函数

//从串口接收数据
byte[] data = new byte[serialPort.BytesToRead];//申请存放数据的缓冲区
serialPort.Read(data, 0, data.Length);//读取数据到data中

//从串口发送数据
byte[] data = null;
 serialPort.Write(sendData, 0, sendData.Length);//从串口发送数据


            

5.2 设置下拉列表不可编辑。

        将ComboBox的DropDownStyle 属性设置为 DropDownList即可。

        

5.3 子线程访问主线程控件(子线程刷新主线程界面)

//使用Invoke访问主线程创建的控件(代理(也即委托)的方式来访问)
            this.Invoke((EventHandler)(delegate
            {
                 //访问主线程控件动作
            }));

5.4 定时器

       System.Timers.Timer timer1 = new System.Timers.Timer();//定时器,用来实现自动发送
       timer1.Interval = Convert.ToInt32(numericTime.Controls[1].Text);//定时器赋初值
       timer1.AutoReset = true;//自动重装初值
       timer1.Start();     //启动定时器
       timer1.Stop();     //停止定时器

猜你喜欢

转载自blog.csdn.net/nanfeibuyi/article/details/85093500
今日推荐