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

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

本次赞助数额为: 1 元 
   源码介绍
串口调试助手

using System;
using System.Drawing;
using System.IO.Ports;
using System.Text;
using System.Windows.Forms;

namespace SerialCommunications
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
            Init();
        }

        private SerialPort ComDevice = new SerialPort();
        Timer timeSend;
        private void Form1_Load(object sender, EventArgs e)
        {
            System.Drawing.Drawing2D.GraphicsPath path = new System.Drawing.Drawing2D.GraphicsPath();
            path.AddEllipse(this.pictureBox1.ClientRectangle);
            Region reg = new Region(path);
            this.pictureBox1.Region = reg;
            this.pictureBox1.BackColor = Color.Red;
            ZDsend.Enabled = false;
        }
        public void Init()
        {
            comboBox_Port.Items.AddRange(SerialPort.GetPortNames());
            if (comboBox_Port.Items.Count > 0)
            {
                comboBox_Port.SelectedIndex = 0;
            }
            else
            {
                MessageBox.Show("未检测到串口");
            }
            comboBox_BaudRate.SelectedIndex = 5;
            comboBox_CheckBits.SelectedIndex = 0;
            comboBox_DataBits.SelectedIndex = 3;
            comboBox_StopBits.SelectedIndex = 0;

        }

        void ComDevice_DataReceived(object sender, SerialDataReceivedEventArgs e)
        {
            byte[] ReDatas = new byte[ComDevice.BytesToRead];
            ComDevice.Read(ReDatas, 0, ReDatas.Length);
            AddData(ReDatas);
        }
        void AddData(byte[] ReDatas)
        {
            if (cbResvTo16.Checked==true)
            {
                foreach (byte b in ReDatas)
                {
                    AddContent(b.ToString("X2"));
                }
            }
            else
            {
                AddContent(Encoding.Default.GetString(ReDatas));
            }
                      
        }
        void AddContent(string str)
        {
            BeginInvoke(new MethodInvoker(delegate
             {
                 textBox_Receive.AppendText(str);
             }));

        }

        private void openOrStop_Click(object sender, EventArgs e)
        {
            if (openOrStop.Text == "开启端口")
            {
                if (comboBox_Port.Items.Count <= 0)
                {
                    MessageBox.Show("未发现可用串口");
                    return;
                }
                if (ComDevice.IsOpen == false)
                {
                    ComDevice.PortName = comboBox_Port.SelectedItem.ToString();
                    ComDevice.BaudRate = Convert.ToInt32(comboBox_BaudRate.SelectedItem.ToString());
                    ComDevice.Parity = (Parity)Convert.ToInt32(comboBox_CheckBits.SelectedIndex.ToString());
                    ComDevice.DataBits = Convert.ToInt32(comboBox_DataBits.SelectedItem.ToString());
                    ComDevice.StopBits = (StopBits)Convert.ToInt32(comboBox_StopBits.SelectedItem.ToString());

                    try
                    {

                        ComDevice.ReceivedBytesThreshold = 1;
                        this.ComDevice.ReadBufferSize = 0x100000;
                        this.ComDevice.WriteBufferSize = 0x5000;
                        ComDevice.DataReceived  = ComDevice_DataReceived;
                        //开启串口
                        ComDevice.Open();
                        button_Send.Enabled = true;
                        ZDsend.Enabled = true;
                    }
                    catch (Exception ex)
                    {
                        MessageBox.Show(ex.Message, "未能成功开启串口", MessageBoxButtons.OK, MessageBoxIcon.Error);
                        return;
                    }
                    openOrStop.Text = "关闭";
                    pictureBox1.BackColor = Color.Green;
                }
                else
                {
                    try
                    {
                        //关闭串口
                        ComDevice.Close();
                        button_Send.Enabled = false;
                    }
                    catch (Exception ex)
                    {
                        MessageBox.Show(ex.Message, "串口关闭错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    }
                    openOrStop.Text = "开启端口";
                    pictureBox1.BackColor = Color.Red;
                }

                comboBox_Port.Enabled = !ComDevice.IsOpen;
                comboBox_BaudRate.Enabled = !ComDevice.IsOpen;
                comboBox_DataBits.Enabled = !ComDevice.IsOpen;
                comboBox_StopBits.Enabled = !ComDevice.IsOpen;
                comboBox_CheckBits.Enabled = !ComDevice.IsOpen;
            }
            else if (openOrStop.Text == "关闭")
            {
                if (ComDevice.IsOpen == true)
                {

                    ComDevice.Close();

                    comboBox_Port.Enabled = !ComDevice.IsOpen;
                    comboBox_BaudRate.Enabled = !ComDevice.IsOpen;
                    comboBox_DataBits.Enabled = !ComDevice.IsOpen;
                    comboBox_StopBits.Enabled = !ComDevice.IsOpen;
                    comboBox_CheckBits.Enabled = !ComDevice.IsOpen;
                    pictureBox1.BackColor = Color.Red;
                    openOrStop.Text = "开启端口";
                    button_Send.Enabled = false;
                    ZDsend.Checked = false;
                    ZDsend.Enabled = false;
                }
            }

        }

        private void ZDsend_CheckedChanged(object sender, EventArgs e)
        {
            if (ZDsend.Checked == true)
            {
                try
                {
                    if (string.IsNullOrEmpty(sendTextBox.Text))
                    {
                        MessageBox.Show("请输入发送内容");
                        ZDsend.Checked = false;
                        return;
                    }
                    if (ZDsend.Checked == true)
                    {
                        timeSend = new Timer();
                        timeSend.Interval = Convert.ToInt32(numTime.Value);
                        timeSend.Tick  = timeSend_Tick;
                        timeSend.Start();
                    }
                }
                catch (Exception)
                {

                    throw;
                }
            }
       
        }


        byte[] strToHexByte(string sendData)
        {

            string hexString = sendData.Replace(" ", "");
            if ((hexString.Length % 2) != 0)
                hexString  = " ";
            byte[] returnBytes = new byte[hexString.Length / 2];
            for (int i = 0; i < returnBytes.Length; i  )
                returnBytes[i] = Convert.ToByte(hexString.Substring(i * 2, 2).Replace(" ", ""), 16);

            return returnBytes;

        }

       void send()
        {
            if (ComDevice.IsOpen)
            {
                if (cbResvTo16Send.Checked == true)
                {
                    string sendData = sendTextBox.Text;
                    ComDevice.Write(strToHexByte(sendData), 0, strToHexByte(sendData).Length);
                }
                else
                {
                    string sendData = sendTextBox.Text;
                    ComDevice.Write(Encoding.Default.GetBytes(sendData), 0, Encoding.Default.GetBytes(sendData).Length);
                }
                // MessageBox.Show("打开");
            }
        }
         void timeSend_Tick(object sender, EventArgs e)
        {
            try
            {
                timeSend.Stop();
                send();

            }
            catch (Exception)
            {

                throw;
            }   
            finally
            {
                timeSend.Start();

            }        
        }

        private void button2_Click(object sender, EventArgs e)
        {
            textBox_Receive.Text = string.Empty;
        }

        private void button3_Click(object sender, EventArgs e)
        {
            sendTextBox.Text = string.Empty;
        }

        private void button_Send_Click(object sender, EventArgs e)
        {
            if (string.IsNullOrEmpty(sendTextBox.Text))
            {
                MessageBox.Show("请输入发送内容");
               
                return;
            }
            send();
        }
    }
}