基本信息
源码名称:串口助手调试源码
源码大小:0.15M
文件格式:.rar
开发语言:C#
更新时间:2019-01-06
   友情提示:(无需注册或充值,赞助后即可获取资源下载链接)

     嘿,亲!知识可是无价之宝呢,但咱这精心整理的资料也耗费了不少心血呀。小小地破费一下,绝对物超所值哦!如有下载和支付问题,请联系我们QQ(微信同号):78630559

本次赞助数额为: 2 元 
   源码介绍
实现串口调试


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

namespace 串口调试器
{
    public partial class Form1 : Form
    {
        //hotkeyWinapi声明:
        [DllImport("user32.dll")]
        [return: MarshalAs(UnmanagedType.Bool)]
        public static extern bool RegisterHotKey(IntPtr hWnd, int id, uint fsModifiers, uint vk);

        [DllImport("user32.dll")]
        [return: MarshalAs(UnmanagedType.Bool)]
        public static extern bool UnregisterHotKey(IntPtr hWnd, int id);
        

        SerialPort sp = new SerialPort();       //声明串口类
        bool stoptb2 = false;

        //发送字节计数
        int fscout = 0;

        //接收字节计数
        int jscout = 0;

        //十六进制显示标志
        bool ishex = false;

        //委托
        delegate void HandleInterfaceUpdateDelegate(string text);  //委托,此为重点
        HandleInterfaceUpdateDelegate interfaceUpdateHandle = null;


        public Form1()
        {
            InitializeComponent();
        }

        //重载函数
        protected override void WndProc(ref Message m)
        {

            //
            const int WM_HOTKEY = 0x0312;

            if (m.Msg == WM_HOTKEY)
            {
                int id = m.WParam.ToInt32();

                //Ctrl Z
                Byte[] byte1 = new Byte[1];
                byte1[0] = 0x1A;

                if (id == 100)
                {
                    if (sp.IsOpen == true)
                    {
                        sp.Write(byte1, 0, 1);
                    }
                }
            }

            base.WndProc(ref m);
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            //初始化状态栏
            toolStripStatusLabel1.Text = "串口调试器正在初始化    ";

            //热键注册Ctrl Alt Z
            RegisterHotKey(this.Handle, 100, 6, Convert.ToUInt32(Keys.Z));

            //初始化combox1
            foreach (string s in SerialPort.GetPortNames())
            {
                comboBox1.Items.Add(s);
            }

            //初始化combox2
            comboBox2.Items.Add("300");
            comboBox2.Items.Add("600");
            comboBox2.Items.Add("1200");
            comboBox2.Items.Add("2400");
            comboBox2.Items.Add("4800");
            comboBox2.Items.Add("9600");
            comboBox2.Items.Add("19200");
            comboBox2.Items.Add("38400");
            comboBox2.Items.Add("76800");
            comboBox2.Items.Add("115200");
            comboBox2.SelectedIndex = 5;

            //初始化combox3
            comboBox3.Items.Add("None");
            comboBox3.Items.Add("Odd");
            comboBox3.Items.Add("Even");
            comboBox3.SelectedIndex = 0;

            //初始化combox4
            comboBox4.Items.Add("8");
            comboBox4.Items.Add("7");
            comboBox4.Items.Add("6");
            comboBox4.SelectedIndex = 0;

            //初始化combox5
            comboBox5.Items.Add("1");
            comboBox5.Items.Add("2");
            comboBox5.SelectedIndex = 0;

            //textbox1初始化
            textBox1.Text = "1000";

            //有串口
            if (comboBox1.Items.Count > 0)
            {
                comboBox1.SelectedIndex = 0;
            
                //串口变量初始化
                sp.PortName = comboBox1.SelectedItem.ToString();
                sp.BaudRate = Convert.ToInt32(comboBox2.SelectedItem.ToString());
                sp.Parity = (Parity)Enum.Parse(typeof(Parity), comboBox3.SelectedItem.ToString());
                sp.DataBits = int.Parse(comboBox4.SelectedItem.ToString());
                sp.StopBits = (StopBits)Enum.Parse(typeof(StopBits), comboBox5.SelectedItem.ToString());
                sp.RtsEnable = true;
                sp.ReceivedBytesThreshold = 1;//设置 DataReceived 事件发生前内部输入缓冲区中的字节数
                sp.DataReceived  = new System.IO.Ports.SerialDataReceivedEventHandler(this.sp_DataReceived);    //DataReceived事件委托

            }
            else
            {
                label9.Text = "未检测到串口";
                label9.ForeColor = Color.Red;
            }

            //委托实例化
            interfaceUpdateHandle = new HandleInterfaceUpdateDelegate(UpdateTextBox);  //实例化委托对象 

            //初始化状态栏
            toolStripStatusLabel1.Text = "串口调试器初始化成功    ";
        }

        //委托的函数
        private void UpdateTextBox(string text)
        {
            if (stoptb2 == false)
            {
                textBox3.Text  = text;
            }

            //更新接收显示
            toolStripStatusLabel3.Text = String.Format(" 接收:{0} 字节    ", jscout);
        }

        //DataReceived事件委托方法
        private void sp_DataReceived(object sender, SerialDataReceivedEventArgs e)
        {
            int readlen = sp.BytesToRead;

            //接收计数
            jscout  = readlen;

            byte[] readBuffer = new byte[sp.ReadBufferSize];
            sp.Read(readBuffer, 0, readBuffer.Length);
            if (ishex)
            {
                string readbuf = null;

                //十六进制格式化数据
                for(int i=0;i<readlen;i  )
                {
                    string s = String.Format("{0:X}", Convert.ToInt32(readBuffer[i]));
                    if (s.Length > 1)
                    {
                        readbuf  = s " ";
                    }
                    else
                    {
                        readbuf  = "0"   s   " ";
                    }
                }
                
                this.Invoke(interfaceUpdateHandle, readbuf);
                    
            }
            else
            {
            
                
                this.Invoke(interfaceUpdateHandle, new string[] { Encoding.UTF8.GetString(readBuffer) });
                
            }
            

        }

        private void button1_Click(object sender, EventArgs e)
        {
            if (sp.IsOpen == false)
            {
                try
                {
                    sp.Open();

                    //清空缓冲区
                    sp.DiscardInBuffer();
                    sp.DiscardOutBuffer();
                }
                catch (Exception)
                {
                    label9.Text = "串口无法连接";
                    return;
                }
                    button1.Text = "断开串口";
                    label6.Text = "已连接";
                    label6.ForeColor = Color.Green;
                    label9.Text = sp.PortName   ","   sp.BaudRate   ","   sp.Parity   ","   sp.DataBits   ","   sp.StopBits;

                    //改变状态栏
                    toolStripStatusLabel1.Text = "  "   label9.Text   "   ";
                
            }
            else
            {
                if (checkBox2.Checked)
                {
                    MessageBox.Show("正在发送,请先停止自动发送");
                    return;
                }
                sp.Close();
                label6.Text = "已断开";
                label6.ForeColor = Color.Red;
                label9.Text = " 串口关闭状态";
                button1.Text = "连接串口";

                //改变状态栏
                toolStripStatusLabel1.Text = "串口关闭状态 不能操作串口";
            }
        }

        private void button2_Click(object sender, EventArgs e)
        {
            if (stoptb2 == false)       //停止显示标志置位
            {
                stoptb2 = true;
                button2.Text = "继续显示";
            }
            else
            {
                stoptb2 = false;                    //停止显示标志复位
                button2.Text = "停止显示";
            }
        }

        private void button3_Click(object sender, EventArgs e)
        {
            textBox3.Text = "";
        }

        private void button4_Click(object sender, EventArgs e)
        {
            if (sp.IsOpen == true)
            {
                fscout  = textBox2.Text.Length;
                sp.Write(textBox2.Text);
                toolStripStatusLabel2.Text = String.Format("  发送:{0} 字节    ", fscout);
            }
            else
            {
                MessageBox.Show("串口未打开");
            }
        }

        private void button5_Click(object sender, EventArgs e)
        {
            fscout = 0;
            toolStripStatusLabel2.Text = "  发送:0 字节    ";
        }

        private void button6_Click(object sender, EventArgs e)
        {
            jscout = 0;
            toolStripStatusLabel3.Text = " 接收:0 字节    ";
        }

        private void button7_Click(object sender, EventArgs e)
        {
            About abFrm = new About();
            abFrm.Owner = this;
            abFrm.ShowDialog();
        }

        //程序退出
        private void button8_Click(object sender, EventArgs e)
        {
            UnregisterHotKey(this.Handle, 100);
            sp.Close();
            this.Close();
        }

        //combox1改变
        private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (sp.IsOpen == false)
            {
                sp.PortName = comboBox1.SelectedItem.ToString();
            }
        }


        //combox2改变
        private void comboBox2_SelectedIndexChanged(object sender, EventArgs e)
        {
            sp.BaudRate = Convert.ToInt32(comboBox2.SelectedItem.ToString());
        }

        //combox3改变
        private void comboBox3_SelectedIndexChanged(object sender, EventArgs e)
        {
            sp.Parity = (Parity)Enum.Parse(typeof(Parity), comboBox3.SelectedItem.ToString());
        }

        //combox4改变
        private void comboBox4_SelectedIndexChanged(object sender, EventArgs e)
        {
            sp.DataBits = int.Parse(comboBox4.SelectedItem.ToString());
        }

        //combox5改变
        private void comboBox5_SelectedIndexChanged(object sender, EventArgs e)
        {
            sp.StopBits = (StopBits)Enum.Parse(typeof(StopBits), comboBox5.SelectedItem.ToString());
        }

        private void checkBox1_CheckedChanged(object sender, EventArgs e)
        {
            if (checkBox1.Checked)
            {
                ishex = true;
            }
            else
            {
                ishex = false;
            }
        }

        private void timer1_Tick(object sender, EventArgs e)
        {
            if (sp.IsOpen == true)
            {
                fscout  = textBox2.Text.Length;
                sp.Write(textBox2.Text);
                toolStripStatusLabel2.Text = String.Format("  发送:{0} 字节    ", fscout);
            }
            else
            {
                MessageBox.Show("串口未打开");
            }
        }

        private void checkBox2_CheckedChanged(object sender, EventArgs e)
        {
            if (sp.IsOpen == false)
            {
                checkBox2.Checked = false;
            }
            else
            {
                timer1.Enabled = checkBox2.Checked;
            }
            
        }

        private void textBox1_TextChanged(object sender, EventArgs e)
        {
            if (textBox1.Text == null||textBox1.Text=="")
            {
                timer1.Interval = 1000;
            }
            else
            {
                timer1.Interval = Convert.ToInt32(textBox1.Text);
            }
        }

        private void checkBox2_Click(object sender, EventArgs e)
        {
            if (sp.IsOpen == false)
            {
                MessageBox.Show("串口未连接");
            }
        }

    }
}