VS2010 C#串口调试助手

原创转载请注明CSDN地址

如有问题,欢迎评论指正,共同进步~

2019.12.25更新:
1.修改win10不能检测系统串口信息的bug。
2.开源。
3.下载
2017.10.18更新:
1.加入停止显示接收的字符。
2.加入定时发送功能,可以循环发送。
4.串口名称支持汉字显示,例如:COM1:通讯端口,
COM4: USB-SERIAL CH340
3.修改部分bug。
完整的工程已经上传到我的csdn资源,需要的可以下载!
[下载]http://download.csdn.net/download/xingkong886/10029983
1.基于vs2010,c#串口。
2.支持热插拔。
3.支持保存接收文件txt格式,可与单片机串口连接发送数据。
4.窗口状态栏显示。
5.登陆界面
6.显示汉字
这里写图片描述
这里写图片描述

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;
using System.IO.Ports;
using System.Text.RegularExpressions;
using System.Threading;
using System.Management;

namespace TEST
{
    public partial class Serial : Form
    {
        public Serial()
        {
            InitializeComponent();
        }
        private SerialPort com = new SerialPort();
        private StringBuilder builder = new StringBuilder();
        private long received_count = 0;//接收计数
        private long send_count = 0;//发送计数
        private string resultFile;
        private string[] ports;
        bool OpenFlag=false;
        private void Serial_Load(object sender, EventArgs e)
        {
            //初始化下拉串口名称列表框
            ports = GetComInfo();
            if(ports!=null)
            {
                comboPortName.Items.Clear();
                comboPortName.Items.AddRange(ports);
            }
            comboPortName.SelectedIndex = comboPortName.Items.Count > 0 ? 0 : -1;
            comboBaudrate.SelectedIndex = comboBaudrate.Items.IndexOf("115200");
            comboBoxstopb.SelectedIndex = comboBoxstopb.Items.IndexOf("1");
            comboBoxdateb.SelectedIndex = comboBoxdateb.Items.IndexOf("8");
            comboBoxjiou.SelectedIndex = comboBoxjiou.Items.IndexOf("无");
            com.DataReceived += com_DataReceived;
            txSend.Text = "01 02 03 04 05 06 07 08";
            txms.Text = "500";
            buttonSend.Enabled = false;
            checkBoxMS.Enabled = false;
        }
        private void Serial_FormClosing(object sender, FormClosingEventArgs e)
        {
            Application.Exit();
        }
        private void buttonopen_Click(object sender, EventArgs e)
        {
            if (com.IsOpen)
            {
                com.Close();
                OpenFlag = false;
            }
            else
            {
                if (comboPortName.Text =="")
                { 
                    MessageBox.Show("请插入串口设备!");
                    return;
                }
                //获得串口端口信息为:  COM1:通讯端口
                string[] coms = comboPortName.Text.Split(':');
                com.PortName =coms[0];
                com.BaudRate = int.Parse(comboBaudrate.Text);//波特率
                com.DataBits = int.Parse(comboBoxdateb.Text);//数据位
                com.Parity = (Parity)Convert.ToInt32(comboBoxjiou.SelectedIndex.ToString());//奇偶校验0-4=no,odd,even,mark,space 
                com.StopBits = (StopBits)Convert.ToInt32(comboBoxstopb.Text);//停止位
                try
                {
                    com.Open();
                }
                catch (Exception ex)
                {
                    MessageBox.Show(ex.Message);
                }
            }
            OpenFlag=com.IsOpen ? true : false;
            //设置按钮的状态
            buttonopen.Text = com.IsOpen ? "关闭串口" : "打开串口";
            buttonSend.Enabled = com.IsOpen ? true:false;
            checkBoxMS.Enabled = com.IsOpen ? true : false;
            checkBoxMS.Checked = false;
            labelopenflag.ForeColor = com.IsOpen ? Color.Red : Color.Black;
        }
       
        public void com_DataReceived(object sender, EventArgs e)
        {
            int n = com.BytesToRead;//获取缓存区字节数
            byte[] buf = new byte[n];//存储串口数据用
            received_count += n;//接收计数
            com.Read(buf, 0, n);//读取缓冲区数据
            builder.Clear();//清除字符串构造器的内容
            this.Invoke((EventHandler)(delegate
            {
                if (checkBoxHexView.Checked)
                {
                    //依次的拼接出16进制字符串
                    foreach (byte b in buf)
                    {
                        builder.Append(b.ToString("X2") + " ");
                    }
                }
                else
                {     
                     builder.Append(Encoding.Default.GetString(buf));
                }
                if (checkBox1.Checked)
                { }
                else
                {
                    this.txGet.AppendText(builder.ToString());                                 
                }
                //修改接收计数
                toolStripStatusLabel4.Text = "Recv:" + received_count.ToString();
            }));
        }
        private void buttonSend_Click(object sender, EventArgs e)
        {
            bool lineflag=false;
            int n = 0;    
            if (checkBoxNewlineSend.Checked)
            {
                lineflag = true;
            }
            //16进制发送
            if (checkBoxHexSend.Checked)
            {
                //正则得到有效的十六进制数(?i)对大小写不敏感,[/da-f],{2}连续出现2次
                MatchCollection mc = Regex.Matches(txSend.Text, @"(?i)[\da-f]{2}");
                List<byte> buf = new List<byte>();
                foreach (Match m in mc)
                {
                    buf.Add(byte.Parse(m.Value, System.Globalization.NumberStyles.HexNumber));
                }
                com.Write(buf.ToArray(), 0, buf.Count);
                if (lineflag == true)
                {
                    com.WriteLine("\r\n");
                    n = buf.Count+2;
                }
                else
                    n = buf.Count;
            }
            else//ASCII发送
            {     
                if (lineflag == true)
                {
                    com.Write(txSend.Text+"\r\n");
                    n = txSend.Text.Length + 2;
                }
                else//不包含换行符
                {
                    com.Write(txSend.Text);
                    n = txSend.Text.Length;
                }
            }
            send_count += n;//累加发送字节数
            toolStripStatusLabel3.Text = "Send:" + send_count.ToString();
        }

        private void buttonReset_Click(object sender, EventArgs e)
        {
            received_count = 0;
            send_count  = 0;
            toolStripStatusLabel3.Text = "Send:0";
            toolStripStatusLabel4.Text = "Recv:0";
        }

        private void btncleanrec_Click(object sender, EventArgs e)
        {
            txGet.Clear();
        }

        private void checkBoxMS_CheckedChanged(object sender, EventArgs e)
        {
            if (checkBoxMS.Checked)
            {
                txSend.Enabled = false;
                timer1.Interval = Convert.ToInt32(txms.Text);
                timer1.Enabled = true;
            }
            else
            {
                txSend.Enabled = true;
                timer1.Enabled = false;
            }
        }
        //热插拔
        protected override void DefWndProc(ref Message m)
        {
            if (m.Msg == 0x0219)
            {
                if (OpenFlag==true)
                {
                    if (com.IsOpen==false)
                    {
                        buttonopen.Text = com.IsOpen ? "关闭串口" : "打开串口";
                        buttonSend.Enabled = com.IsOpen ? true : false;
                        labelopenflag.ForeColor = com.IsOpen ? Color.Red : Color.Black;
                        comboPortName.SelectedIndex = comboPortName.Items.Count > 0 ? 0 : -1;
                    }
                }   
            }
            base.DefWndProc(ref m);
        }
        private void comboPortName_Click(object sender, EventArgs e)
        {
            int Index = comboPortName.SelectedIndex;
            ports = GetComInfo();
            if(ports!=null)
            {
                comboPortName.Items.Clear();
                comboPortName.Items.AddRange(ports);
                if (Index <= comboPortName.Items.Count - 1)
                    comboPortName.SelectedIndex = Index;

            }
        }
        //定时点击发送按钮
        private void timer1_Tick(object sender, EventArgs e)
        {
            buttonSend.PerformClick();
        }

        private void toolStripStatusLabel2_Click(object sender, EventArgs e)
        {
            System.Diagnostics.Process.Start("http://blog.csdn.net/xingkong886");  
        }

        private void btnsave_Click(object sender, EventArgs e)
        {         
            if (txGet.Text == "")
            {
                MessageBox.Show("没有数据保存!","错误");
                return;
            }     
            SaveFileDialog SaveFile = new SaveFileDialog();
            SaveFile.Filter = "All files(*.*)|*.*|txt files(*.txt)|*.txt";//文本筛选
            SaveFile.FilterIndex = 3;//文本筛选器索引,选择第一项就是1
            SaveFile.RestoreDirectory = true;
            if (SaveFile.ShowDialog() == DialogResult.OK)
            {
                resultFile = SaveFile.FileName;
                StreamWriter sw = File.CreateText(resultFile);
                sw.WriteLine(DateTime.Now.ToString());
                sw.Write(txGet.Text);
                sw.Close();
            }
        }
        //获得串口信息
        public static string[] GetComInfo()
        {
            List<string> Comstrs = new List<string>();
            try
            {
                using (ManagementObjectSearcher searcher = new ManagementObjectSearcher("select * from Win32_PnPEntity where Name like '%(COM%'"))
                {
                    var hardInfos = searcher.Get();
                    foreach (var comInfo in hardInfos)
                    {
                        if (comInfo.Properties["Name"].Value.ToString().Contains("COM"))
                        {
                            //通讯端口(COM1) 转变为 COM1:通讯端口
                            string com = comInfo.Properties["Name"].Value.ToString();
                            string[] strcom = com.Split(new char[2] { '(', ')' });
                            Comstrs.Add(strcom[1] + ":" + strcom[0]);
                        }
                    }
                    searcher.Dispose();
                }
                return Comstrs.ToArray();
            }
            catch
            {
                return null;
            }
            finally
            { Comstrs = null; }
        }
    }
}


©️2020 CSDN 皮肤主题: 创作都市 设计师:CSDN官方博客 返回首页