在好例子网,分享、交流、成长!
您当前所在位置:首页C# 开发实例C#语言基础 → C# 串口调试助手 源码

C# 串口调试助手 源码

C#语言基础

下载此实例
  • 开发语言:C#
  • 实例大小:2.16M
  • 下载次数:167
  • 浏览次数:805
  • 发布时间:2018-02-23
  • 实例类别:C#语言基础
  • 发 布 人:bdzjw
  • 文件格式:.rar
  • 所需积分:2
 相关标签: 串口调试助手 串口 调试

同类人气实例

实例介绍

【实例简介】

【实例截图】

【核心代码】

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

using System.Runtime.InteropServices;//引用命名空间

namespace zzzz
{
    public partial class Form1 : Form
    {
        bool btn = false;
        int received_count = 0;//Convert.ToInt32(ContentValue(strSec, "SendCount"));//接收计数
        int send_count = 0;//Convert.ToInt32(ContentValue(strSec, "ReceCount"));//发送计数
        bool send_hex = false;
        //public static int WriteTextNum = 1;
        //int WriteTextFlag = 1;
        int chekFlag;
        string localFilePath = "";

        public Form1()
        {
            InitializeComponent();
            Control.CheckForIllegalCrossThreadCalls = false;
        }

        private void button1_MouseHover(object sender, EventArgs e)
        {
            //button1.BackgroundImage = Properties.Resources.chinaz3;
            toolStripSplitButton1.Image = Properties.Resources.chinaz3;
        }

        private void button1_Click(object sender, EventArgs e)
        {
            if (btn == false && comboBox1.Text != "")
            {
                //button1.BackgroundImage = Properties.Resources.chinaz5;
                try
                {
                    serialPort1.PortName = comboBox1.Text;//串口号
                    serialPort1.BaudRate = Convert.ToInt32(comboBox2.Text);//波特率
                    serialPort1.Parity =  (Parity)Enum.Parse(typeof(Parity),comboBox3.Text);//校验位
                    serialPort1.DataBits = Convert.ToInt32(comboBox4.Text.ToString().Substring(0,1));//数据位
                    serialPort1.StopBits = (StopBits)Enum.Parse(typeof(StopBits), comboBox5.Text.ToString().Substring(0, 1)); //停止位
                    serialPort1.Encoding = System.Text.Encoding.GetEncoding("GB2312");
                    serialPort1.Open();
                    toolStripStatusLabel1.Text = "串口已连接";
                    button1.Text = "关闭串口";
                    //button1.BackgroundImage = Properties.Resources.chinaz5;
                    toolStripSplitButton1.Image = Properties.Resources.chinaz5;
                }
                catch {
                    //button1.BackgroundImage = Properties.Resources.chinaz4;
                    MessageBox.Show("打开串口失败,请重新选择端口号或检查连接", "提示");
                    serialPort1.Close();
                    button1.Text = "打开串口";
                }
                btn = true;
            }
            else {
                serialPort1.Close();
                button1.Text = "打开串口";
                toolStripStatusLabel1.Text = "串口未连接";
                toolStripSplitButton1.Image = Properties.Resources.chinaz4;
                btn = false;
            }
        }

        private void button1_MouseLeave(object sender, EventArgs e)
        {
            if (btn == true)
            {
                toolStripSplitButton1.Image = Properties.Resources.chinaz5;
            }
            else {
                toolStripSplitButton1.Image = Properties.Resources.chinaz4;
            }
        }
        
        private void Form1_Load(object sender, EventArgs e)
        {
            serialPort1.Encoding = System.Text.Encoding.GetEncoding("GB2312");
            toolStripStatusLabel1.Text = "请先打开串口";
            toolStripStatusLabel8.Text = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");
            richTextBox1.ScrollBars = RichTextBoxScrollBars.ForcedVertical;
            richTextBox2.ScrollBars = RichTextBoxScrollBars.ForcedVertical;
            dataGridView1.AllowUserToAddRows = false;
            this.Width = 750;
            comboBox1.Items.Clear();
            foreach (string vPortName in SerialPort.GetPortNames())
            {
                comboBox1.Items.Add(vPortName);
            }
            //richTextBox1.Text = comboBox1.Items.Count.ToString() vPortName1 comboBox1.Items[comboBox1.Items.Count - 1];
            if (comboBox1.Items.Count != 0)
            {
                
                comboBox2.Text = "9600";
                comboBox3.Text = "None";
                comboBox4.Text = "8位";
                comboBox5.Text = "1位";
                ReadIni();
                try
                {
                    comboBox1.Text = Convert.ToString(comboBox1.Items[comboBox1.Items.Count - 1]);
                    received_count = Convert.ToInt32(ContentValue(strSec, "SendCount"));//接收计数
                    send_count = Convert.ToInt32(ContentValue(strSec, "ReceCount"));//发送计数
                }
                catch {
                }
            }
            else {
                 MessageBox.Show("当前设备不存在串口,请检查硬件后点击“扫描”", "提示");
            }
            
            /*****************非常重要************************/

            serialPort1.DataReceived = Port_DataReceived;//new SerialDataReceivedEventHandler(Port_DataReceived);//必须手动添加事件处理程序
        }

        private void label6_Click(object sender, EventArgs e)
        {
            richTextBox1.Clear();
        }

        private void label7_Click(object sender, EventArgs e)
        {
            richTextBox2.Clear();
        }

        private void checkBox4_CheckedChanged(object sender, EventArgs e)
        {
            if (checkBox4.Checked)
            {
                send_hex = true;
            }
            else
            {
                send_hex = false;  
            }
        }


        private byte[] StringToBytes(string TheString)      //转字符                                    //utf8编码转GB2132编码
        {
            Encoding FromEcoding = Encoding.GetEncoding("UTF-8");                               //UTF8编码
            Encoding ToEcoding = Encoding.GetEncoding("gb2312");                                //GB2312编码
            byte[] FromBytes = FromEcoding.GetBytes(TheString);                                 //获取汉字UTF8字节序列
            byte[] Tobytes = Encoding.Convert(FromEcoding, ToEcoding, FromBytes);               //转换为GB2132字节码
            return Tobytes;                                                                     //返回
        }

        private string BytesToString(byte[] Bytes)        //转汉字                                      //过程同上
        {
            string Mystring;
            Encoding FromEcoding = Encoding.GetEncoding("gb2312");
            Encoding ToEcoding = Encoding.GetEncoding("UTF-8");
            byte[] Tobytes = Encoding.Convert(FromEcoding, ToEcoding, Bytes);
            Mystring = ToEcoding.GetString(Tobytes);                                            //得到的是UTF8字节码序列,需要转换为UTF8字符串
            return Mystring;                                                                    //转换
        }

        private void SendData()
        {
            byte[] Data = new byte[1];
            if (serialPort1.IsOpen && richTextBox2.Text != "")
            {
                if (!checkBox6.Checked)
                {
                    toolStripStatusLabel7.Text = richTextBox2.Text;
                    try
                    {
                        serialPort1.Write(richTextBox2.Text);
                        send_count = richTextBox2.Text.Length;
                        toolStripStatusLabel3.Text = send_count.ToString();
                    }
                    catch
                    {
                        toolStripStatusLabel7.Text = "串口数据写入错误";
                        //serialPort1.Close();
                    }
                }
                else
                {
                    try
                    {
                        string buffer = richTextBox2.Text;
                        buffer = buffer.Replace("0x", "");                                    //为了保证汉字转编码输出结果(0xXX)可以通用,所以程序允许输入0xXX(可以带空格),程序会将0x和空格自动去除
                        buffer = buffer.Replace(" ", string.Empty);
                        for (int i = 0; i < buffer.Length / 2; i )
                        {
                            Data[0] = Convert.ToByte(buffer.Substring(i * 2, 2), 16);
                            toolStripStatusLabel7.Text = Data[0];
                            serialPort1.Write(Data, 0, 1);//循环发送(如果输入字符为0A0BB,则只发送0A,0B)
                            send_count = 1;
                            toolStripStatusLabel3.Text = send_count.ToString();
                        }
                        if (buffer.Length % 2 != 0)
                        {
                            Data[0] = Convert.ToByte(buffer.Substring(buffer.Length - 1, 1), 16);//单独发送B(0B)
                            serialPort1.Write(Data, 0, 1);//发送
                            send_count = 1;
                            toolStripStatusLabel3.Text = send_count.ToString();
                        }
                    }
                    catch {
                        //toolStripStatusLabel7.Text = "数据错误,请重新输入";
                    }
                }
                toolStripStatusLabel7.Text = "数据发送成功";
                timer2.Start();
            }
        }

        private void button2_Click(object sender, EventArgs e)
        {
            if (serialPort1.IsOpen && richTextBox2.Text != "")
            {
                if (button2.Text == "发 送")
                {
                    if (send_hex)
                    {
                        timer1.Start();
                        button2.Text = "停止发送";
                        button1.Enabled= false;
                    }
                    else
                    {
                        SendData();
                    }
                    if (checkBox5.Checked) richTextBox2.Clear();
                }
                else
                {
                    timer1.Stop();
                    button2.Text = "发 送";
                    button1.Enabled = true;
                }
            }
            else if(!serialPort1.IsOpen)
            toolStripStatusLabel7.Text = "请打开串口";
            else if (richTextBox2.Text == "")
            toolStripStatusLabel7.Text = "请在发送区输入数据";
            timer2.Start();
        }

        private void timer1_Tick(object sender, EventArgs e)
        {
            timer1.Stop();
            SendData();
            timer1.Start();
        }

        private void textBox1_TextChanged(object sender, EventArgs e)
        {
            timer1.Interval = Convert.ToInt32(textBox1.Text);
        }

        private void Port_DataReceived(object sender, SerialDataReceivedEventArgs e)//串口数据接收事件
        {
            //Control.CheckForIllegalCrossThreadCalls = false;
            System.Threading.Thread.Sleep(50);//延时50ms等待接收完数据
            //timer2.Start();
            if (!checkBox1.Checked)//如果接收模式为字符模式
            {
                try
                {
                    int len = serialPort1.BytesToRead;
                    Byte[] readBuffer = new Byte[len];
                    serialPort1.Read(readBuffer, 0, len);
                    if (!checkBox2.Checked)
                        richTextBox1.Text = BytesToString(readBuffer);
                    received_count = len;
                }
                catch {
                }
            }
            else
            { //如果接收模式为数值接收
                try
                {
                    int len = serialPort1.BytesToRead;
                    Byte[] readBuffer = new Byte[len];
                    serialPort1.Read(readBuffer, 0, len);
                    foreach (byte str in readBuffer)
                    {
                        if (!checkBox2.Checked)
                            richTextBox1.AppendText(str.ToString("X2") " ");
                    }
                    received_count = readBuffer.Length;
                }
                catch {
                }
            }
            if (checkBox3.Checked && !checkBox2.Checked) richTextBox1.AppendText("\r\n");
            toolStripStatusLabel5.Text = received_count.ToString();
            //timer2.Start();
            toolStripStatusLabel7.Text = "接收到数据";
            
            try
            {
                serialPort1.DiscardInBuffer();//释放接收缓冲区数据
            }
            catch {
            }
            timer2.Start();
        }

        //private void timer2_Tick(object sender, EventArgs e)
        //{
        //    timer2.Stop();
        //    toolStripStatusLabel7.Text = "";
        //}

        private void button3_Click(object sender, EventArgs e)
        {
            comboBox1.Items.Clear();
            foreach (string vPortName in SerialPort.GetPortNames())
            {
                comboBox1.Items.Add(vPortName);
            }
            if (comboBox1.Items.Count != 0)
            {
                comboBox1.Text = Convert.ToString(comboBox1.Items[comboBox1.Items.Count - 1]);
                comboBox2.Text = "9600";
                comboBox3.Text = "None";
                comboBox4.Text = "8位";
                comboBox5.Text = "1位";
            }
            toolStripStatusLabel7.Text = "扫描出" comboBox1.Items.Count.ToString() "个串口,请选择";
        }

        private void label10_Click(object sender, EventArgs e)
        {
            SaveFileDialog sfd = new SaveFileDialog();
            sfd.Title = "";
            //sfd.InitialDirectory = @"D:\";
            sfd.InitialDirectory = @localFilePath;
            sfd.Filter = "文本文件| *.txt";
            //sfd.ShowDialog();
            
            //保存对话框是否记忆上次打开的目录
            sfd.RestoreDirectory = true;
            if (sfd.ShowDialog() == DialogResult.OK)
                localFilePath = sfd.FileName.ToString();
            string path = sfd.FileName;
            if (path == "")
            {
                return;
            }

            using (FileStream fsWrite = new FileStream(path, FileMode.OpenOrCreate, FileAccess.Write))
            {
                byte[] buffer = Encoding.Default.GetBytes(richTextBox1.Text);
                fsWrite.Write(buffer, 0, buffer.Length);
                MessageBox.Show("保存成功");

            }
            //FileStream file = new FileStream("记录.txt", FileMode.Create, FileAccess.ReadWrite, FileShare.ReadWrite);//建立一个文件
            //StreamWriter writer = new StreamWriter(file); //设置文件时可以写的
            //writer.WriteLine(textBox2.Text);
            //writer.Close();
            //file.Close();
        }

        private void label11_Click(object sender, EventArgs e)
        {
            OpenFileDialog ofd = new OpenFileDialog();
            ofd.Title = "请选择要打开的文件";
            //多选
            ofd.Multiselect = true;
            //初始目录
            ofd.InitialDirectory = @localFilePath;
            //设定文件类型
            ofd.Filter = "文本文件 | *.txt";
            ofd.ShowDialog();

            //获得在打开文件对话框中选择的文件的路径
            string path = ofd.FileName;
            if (path == "")
            {
                return;
            }
            using (FileStream fsRead = new FileStream(path, FileMode.OpenOrCreate, FileAccess.Read))
            {
                byte[] buffer = new byte[1024 * 1024 * 5];
                int r = fsRead.Read(buffer, 0, buffer.Length);
                richTextBox2.Text = Encoding.Default.GetString(buffer, 0, r);
            }
        }
        

        #region "声明变量"

        /// <summary>
        /// 写入INI文件
        /// </summary>
        /// <param name="section">节点名称[如[TypeName]]</param>
        /// <param name="key">键</param>
        /// <param name="val">值</param>
        /// <param name="filepath">文件路径</param>
        /// <returns></returns>
        [DllImport("kernel32")]
        private static extern long WritePrivateProfileString(string section, string key, string val, string filepath);
        /// <summary>
        /// 读取INI文件
        /// </summary>
        /// <param name="section">节点名称</param>
        /// <param name="key">键</param>
        /// <param name="def">值</param>
        /// <param name="retval">stringbulider对象</param>
        /// <param name="size">字节大小</param>
        /// <param name="filePath">文件路径</param>
        /// <returns></returns>
        [DllImport("kernel32")]
        private static extern int GetPrivateProfileString(string section, string key, string def, StringBuilder retval, int size, string filePath);

        private string strFilePath = AppDomain.CurrentDomain.BaseDirectory "SerialConfig.ini";//@"C:\Users\Public\Documents\TEMP\SerialConfig.ini";//获取INI文件路径System.Environment.CurrentDirectory  Application.StartupPath
        private string strSec = ""; //INI文件名

        #endregion

              
        //读取
        private void ReadIni() //btnRead_Click(object sender, EventArgs e) 
        {
                if (File.Exists(strFilePath))//读取时先要判读INI文件是否存在
                {

                    strSec = Path.GetFileNameWithoutExtension(strFilePath);
                    comboBox1.Text = ContentValue(strSec, "PortName");
                    comboBox2.Text = ContentValue(strSec, "BandRate");
                    comboBox3.Text = ContentValue(strSec, "Parity");
                    comboBox4.Text = ContentValue(strSec, "DataBits") "位";
                    comboBox5.Text = ContentValue(strSec, "StopBits") "位";
                    checkBox1.Checked = bool.Parse(ContentValue(strSec, "ReceivHex"));
                    checkBox2.Checked = bool.Parse(ContentValue(strSec, "ReceivBlank"));
                    checkBox3.Checked = bool.Parse(ContentValue(strSec, "ReceivLine"));
                    checkBox6.Checked = bool.Parse(ContentValue(strSec, "SendHex"));
                    checkBox5.Checked = bool.Parse(ContentValue(strSec, "SendBlank"));
                    checkBox4.Checked = bool.Parse(ContentValue(strSec, "SendAuto"));
                    textBox1.Text = ContentValue(strSec, "SendMs");
                    toolStripStatusLabel3.Text = ContentValue(strSec, "SendCount");
                    toolStripStatusLabel5.Text = ContentValue(strSec, "ReceCount");
                    this.Width = Convert.ToInt32(ContentValue(strSec, "FormWidth"));
                    if (this.Width == 1125) label12.Text = "扩展功能收回<<";
                    else label12.Text = "扩展功能展开>>";
                    int CountN = Convert.ToInt32(ContentValue(strSec, "RowCount"));
                    for (int i = 0; i < CountN; i )//dataGridView1.Rows.Count;//所有行数
                    {
                        int index = dataGridView1.Rows.Add();
                        //dataGridView1.Rows[index].Cells[0].Value = richTextBox2.Text;
                        dataGridView1.Rows[index].Cells[0].Value = ContentValue(strSec, "ComandCount" i.ToString());
                    }
                }
                else
                {
                    //MessageBox.Show("INI文件不存在");
                }
        }

        /// <summary>
        /// 自定义读取INI文件中的内容方法
        /// </summary>
        /// <param name="Section">键</param>
        /// <param name="key">值</param>
        /// <returns></returns>
        private string ContentValue(string Section, string key)
        {
            StringBuilder temp = new StringBuilder(1024);
            GetPrivateProfileString(Section, key, "", temp, 1024, strFilePath);
            return temp.ToString();
        }

        private void Form1_FormClosing(object sender, FormClosingEventArgs e)
        {
            try
            {
                //根据INI文件名设置要写入INI文件的节点名称
                //此处的节点名称完全可以根据实际需要进行配置
                if (comboBox1.Text != "")
                {
                    serialPort1.Close();
                    strSec = Path.GetFileNameWithoutExtension(strFilePath);
                    WritePrivateProfileString(strSec, "PortName", comboBox1.Text.Trim(), strFilePath);
                    WritePrivateProfileString(strSec, "BandRate", comboBox2.Text.Trim(), strFilePath);
                    WritePrivateProfileString(strSec, "Parity", comboBox3.Text.Trim(), strFilePath);
                    WritePrivateProfileString(strSec, "DataBits", comboBox4.Text.Substring(0, 1).Trim(), strFilePath);
                    WritePrivateProfileString(strSec, "StopBits", comboBox5.Text.Substring(0, 1).Trim(), strFilePath);
                    WritePrivateProfileString(strSec, "ReceivHex", checkBox1.Checked ? "true" : "false", strFilePath);
                    WritePrivateProfileString(strSec, "ReceivBlank", checkBox2.Checked ? "true" : "false", strFilePath);
                    WritePrivateProfileString(strSec, "ReceivLine", checkBox3.Checked ? "true" : "false", strFilePath);
                    WritePrivateProfileString(strSec, "SendHex", checkBox6.Checked ? "true" : "false", strFilePath);
                    WritePrivateProfileString(strSec, "SendBlank", checkBox5.Checked ? "true" : "false", strFilePath);
                    WritePrivateProfileString(strSec, "SendAuto", checkBox4.Checked ? "true" : "false", strFilePath);
                    WritePrivateProfileString(strSec, "SendMs", textBox1.Text, strFilePath);
                    WritePrivateProfileString(strSec, "SendCount", toolStripStatusLabel3.Text, strFilePath);
                    WritePrivateProfileString(strSec, "ReceCount", toolStripStatusLabel3.Text, strFilePath);
                    WritePrivateProfileString(strSec, "FormWidth", this.Size.Width.ToString(), strFilePath);
                    WritePrivateProfileString(strSec, "RowCount", dataGridView1.Rows.Count.ToString(), strFilePath);
                    for (int i = 0; i < dataGridView1.Rows.Count; i )//dataGridView1.Rows.Count;//所有行数
                    {
                        this.dataGridView1.CurrentCell = this.dataGridView1[0, i];
                        WritePrivateProfileString(strSec, "ComandCount" i.ToString(), dataGridView1.CurrentCell.Value.ToString(), strFilePath);
                    }
                    //MessageBox.Show("写入成功");
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message.ToString());
            }
        }

        private void richTextBox2_TextChanged(object sender, EventArgs e)
        {
            if (checkBox6.Checked && chekFlag == 0)
            {
                string str = richTextBox2.Text;
                
                if (str.Length > 2)
                {
                    int WriteTextNum = str.Length  / 3;
                    if (str.Length == (WriteTextNum * 3) && str.Substring(str.Length - 2, 1) != " ")
                    {
                        //WriteTextNum ;
                        if (str.Substring(str.Length - 1, 1) != " ")
                            richTextBox2.Text = str.Substring(0, str.Length - 1) " " str.Substring(str.Length - 1, 1);
                        else richTextBox2.Text = str.Substring(0, str.Length - 1);
                        richTextBox2.Select(richTextBox2.Text.Length, 0);//选择文本末尾位置
                        richTextBox2.ScrollToCaret();//将光标滚动到末尾位置,不然追加一个空格光标会跳转到开头位置
                    }
                }
            }
        }
        
        private void richTextBox2_KeyPress(object sender, KeyPressEventArgs e)
        {
            if(checkBox6.Checked)
            {
                if ((int)e.KeyChar >= 48 & (int)e.KeyChar <= 57 | (int)e.KeyChar == 8 | (int)e.KeyChar >= 65 & (int)e.KeyChar <= 70 | (int)e.KeyChar >= 97 & (int)e.KeyChar <= 102)
                {
                    e.Handled = false;
                }
                else
                {
                    e.Handled = true;
                    toolStripStatusLabel7.Text = "请输入合法数字0~9,A~F";
                    timer2.Start();
                }

                if ((int)e.KeyChar >= 97 && (int)e.KeyChar <= 102)
                {
                    e.KeyChar = (char)((int)e.KeyChar - 32);
                }

                //if (e.KeyChar == '\b' && richTextBox2.Text.Length > 1 && richTextBox2.Text.Length % 3 == 0)
                //{
                //    string str = richTextBox2.Text;
                //    try
                //    {
                //        if (str.Substring(str.Length - 1, 1) == " ") WriteTextFlag = 0;
                //        else WriteTextFlag = 1;
                //        if (WriteTextFlag == 0)
                //        {
                //            //WriteTextNum--;
                //            //if (WriteTextNum == 1) WriteTextNum = 1;
                //        }
                //        richTextBox2.Select(richTextBox2.Text.Length, 0);//选择文本末尾位置
                //        richTextBox2.ScrollToCaret();//将光标滚动到末尾位置,不然追加一个空格光标会跳转到开头位置
                //    }
                //    catch { }
                //    //richTextBox2.Text = str.Substring(0, str.Length - 2);
                //    //richTextBox2.Select(richTextBox2.Text.Length, 0);
                //    //richTextBox2.ScrollToCaret();
                //} 
            }
        }

        private void Form1_Resize(object sender, EventArgs e)
        {
            this.Height = 514;
            if (this.Size.Width <= 512) this.Width = 512;
        }

        private void timer3_Tick(object sender, EventArgs e)
        {
            toolStripStatusLabel8.Text = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");
        }

        private void toolStripDropDownButton1_Click(object sender, EventArgs e)
        {
            received_count = 0;//接收计数
            send_count = 0;//发送计数
            toolStripStatusLabel3.Text = send_count.ToString();
            toolStripStatusLabel5.Text = received_count.ToString();
        }

        private void button4_Click(object sender, EventArgs e)
        {
            received_count = 0;//接收计数
            send_count = 0;//发送计数
            toolStripStatusLabel3.Text = send_count.ToString();
            toolStripStatusLabel5.Text = received_count.ToString();
        }

        private void checkBox6_CheckedChanged(object sender, EventArgs e)
        {
            chekFlag = 1;
            if (checkBox6.Checked)
            {
                string str = richTextBox2.Text;
                
                richTextBox2.Text = "";
                foreach(byte bty in str)
                {
                    richTextBox2.AppendText(bty.ToString("X2") " "); 
                }
                chekFlag = 0;
            }
            else {
                byte data;
                
                string str = richTextBox2.Text;
                richTextBox2.Text = "";
                str = str.Replace(" ","");
                str = str.Replace("0x","");
                for(int i = 0;i<str.Length/2;i )
                {
                    try
                    {
                        data = Convert.ToByte(str.Substring(i * 2, 2), 16);
                        richTextBox2.Text = (char)data;
                        //send_count = richTextBox2.Text.Length / 3;
                    }
                    catch { }
                }
                chekFlag = 0;
            }
        }

        private void timer2_Tick(object sender, EventArgs e)
        {
            //timer2.Stop();
            //timer2.Enabled = 
            toolStripStatusLabel7.Text = "";
        }

        private void button5_Click(object sender, EventArgs e)
        {
            int index = dataGridView1.Rows.Add();
            dataGridView1.Rows[index].Cells[0].Value = richTextBox2.Text;
            //WriteTextNum = 1;
            richTextBox2.Text = "";
        }

        private void SendData0()
        {
            byte[] Data = new byte[1];
            if (serialPort1.IsOpen && dataGridView1.CurrentCell.Value.ToString() != "")
            {
                if (!checkBox6.Checked)
                {
                    try
                    {
                        serialPort1.Write(dataGridView1.CurrentCell.Value.ToString());
                        send_count = richTextBox2.Text.Length;
                        toolStripStatusLabel3.Text = send_count.ToString();
                    }
                    catch
                    {
                        toolStripStatusLabel7.Text = "串口数据写入错误";
                        //serialPort1.Close();
                    }
                }
                else
                {
                    try
                    {
                        string buffer = dataGridView1.CurrentCell.Value.ToString();
                        buffer = buffer.Replace("0x", "");                                    //为了保证汉字转编码输出结果(0xXX)可以通用,所以程序允许输入0xXX(可以带空格),程序会将0x和空格自动去除
                        buffer = buffer.Replace(" ", string.Empty);
                        for (int i = 0; i < buffer.Length / 2; i )
                        {
                            Data[0] = Convert.ToByte(buffer.Substring(i * 2, 2), 16);
                            toolStripStatusLabel7.Text = Data[0];
                            serialPort1.Write(Data, 0, 1);//循环发送(如果输入字符为0A0BB,则只发送0A,0B)
                            send_count = 1;
                            toolStripStatusLabel3.Text = send_count.ToString();
                        }
                        if (buffer.Length % 2 != 0)
                        {
                            Data[0] = Convert.ToByte(buffer.Substring(buffer.Length - 1, 1), 16);//单独发送B(0B)
                            serialPort1.Write(Data, 0, 1);//发送
                            send_count = 1;
                            toolStripStatusLabel3.Text = send_count.ToString();
                        }
                    }
                    catch
                    {
                        //toolStripStatusLabel7.Text = "数据错误,请重新输入";
                    }
                }
                toolStripStatusLabel7.Text = "数据发送成功";
                timer2.Start();
            }
        }

        private void button7_Click(object sender, EventArgs e)
        {
            //richTextBox2.Text = dataGridView1.CurrentCell.Value.ToString();
            if (serialPort1.IsOpen && dataGridView1.CurrentCell.Value.ToString() != "")
            {
                 SendData0();
            }
            else if (!serialPort1.IsOpen)
                toolStripStatusLabel7.Text = "请打开串口";
            else if (richTextBox2.Text == "")
                toolStripStatusLabel7.Text = "请在发送区输入数据";
            timer2.Start();
        }

        private void button6_Click(object sender, EventArgs e)
        {
            try
            {
                int RowNumber;
                if (null == dataGridView1.CurrentCell)
                {
                    return;
                }
                RowNumber = dataGridView1.CurrentCell.RowIndex;
                dataGridView1.Rows.RemoveAt(RowNumber);
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.ToString());
            }
        }
        
        private void label12_Click(object sender, EventArgs e)
        {
            if (this.Width == 750)
            {
                this.Width = 1125;
                label12.Text = "扩展功能收回<<";
            }
            else {
                this.Width = 750;
                label12.Text = "扩展功能展开>>";
            }
        }
    }
}

实例下载地址

C# 串口调试助手 源码

不能下载?内容有错? 点击这里报错 + 投诉 + 提问

好例子网口号:伸出你的我的手 — 分享

网友评论

第 1 楼 lvninglu 发表于: 2018-04-14 18:51 13
为什么解压时,提示文件已损坏??

支持(0) 盖楼(回复)

第 2 楼 星火燎原 发表于: 2018-04-14 23:02 25
为什么解压时,提示文件已损坏??

lvninglu 2018-04-14 18:51 13

请不要使用迅雷下载工具下载,用浏览器默认下载即可 下载完整无损包

支持(0) 盖楼(回复)

发表评论

(您的评论需要经过审核才能显示)

查看所有4条评论>>

小贴士

感谢您为本站写下的评论,您的评论对其它用户来说具有重要的参考价值,所以请认真填写。

  • 类似“顶”、“沙发”之类没有营养的文字,对勤劳贡献的楼主来说是令人沮丧的反馈信息。
  • 相信您也不想看到一排文字/表情墙,所以请不要反馈意义不大的重复字符,也请尽量不要纯表情的回复。
  • 提问之前请再仔细看一遍楼主的说明,或许是您遗漏了。
  • 请勿到处挖坑绊人、招贴广告。既占空间让人厌烦,又没人会搭理,于人于己都无利。

关于好例子网

本站旨在为广大IT学习爱好者提供一个非营利性互相学习交流分享平台。本站所有资源都可以被免费获取学习研究。本站资源来自网友分享,对搜索内容的合法性不具有预见性、识别性、控制性,仅供学习研究,请务必在下载后24小时内给予删除,不得用于其他任何用途,否则后果自负。基于互联网的特殊性,平台无法对用户传输的作品、信息、内容的权属或合法性、安全性、合规性、真实性、科学性、完整权、有效性等进行实质审查;无论平台是否已进行审查,用户均应自行承担因其传输的作品、信息、内容而可能或已经产生的侵权或权属纠纷等法律责任。本站所有资源不代表本站的观点或立场,基于网友分享,根据中国法律《信息网络传播权保护条例》第二十二与二十三条之规定,若资源存在侵权或相关问题请联系本站客服人员,点此联系我们。关于更多版权及免责申明参见 版权及免责申明

;
报警