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

     嘿,亲!知识可是无价之宝呢,但咱这精心整理的资料也耗费了不少心血呀。小小地破费一下,绝对物超所值哦!如有下载和支付问题,请联系我们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 ComTool
{
    /*---------------作者:叶知秋----------------------*/
    /*---------------时间:2012年12月6日---------------*/
    /*---------------邮箱:yq@yyzq.net---------*/
    /*---------------www.yyzq.net--------------------------*/
    /*本人兼职各类软硬件系统集成,RFID系统集成,工控测试系统开发。*/
    /*任何个人均可免费修改,使用本程序,但请保留以上作者信息,谢谢!*/

    public partial class Form1 : Form
    {
        SerialPort ComDevice = new SerialPort();
        bool AllowReceive = true;
        SubWin.CheckWin Cwin = new SubWin.CheckWin();
        SubWin.ByteCaculator BCWin = new SubWin.ByteCaculator();

        public Form1()
        {
            InitializeComponent();
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            lblVersion.Text  = AssemblyLib.AssemblyVersion;
            //获取可用串口列表
            string[] ports = SerialPort.GetPortNames();
            foreach (string port in ports)
            {
                drpComList.Items.Add(port);
            }
            if (drpComList.Items.Count > 0)
            {
                drpComList.SelectedIndex = 0;
                btnCom.Enabled = true;
            }
            drpBaudRate.SelectedIndex = 5;
            drpParity.SelectedIndex = 0;
            drpDataBits.SelectedIndex = 0;
            drpStopBits.SelectedIndex = 0;
            ComDevice.DataReceived =new SerialDataReceivedEventHandler(ComDevice_DataReceived);
        }
        
        private void btnCom_Click(object sender, EventArgs e)
        {
            if (btnCom.Tag.ToString() == "0")
            {
                ComDevice.PortName = drpComList.SelectedItem.ToString();
                ComDevice.BaudRate = Convert.ToInt32(drpBaudRate.SelectedItem.ToString());
                ComDevice.Parity = (Parity)Convert.ToInt32(drpParity.SelectedIndex.ToString());
                ComDevice.DataBits = Convert.ToInt32(drpDataBits.SelectedItem.ToString());
                ComDevice.StopBits = (StopBits)Convert.ToInt32(drpStopBits.SelectedItem.ToString());
                try
                {
                    ComDevice.Open();
                }
                catch (Exception ex)
                {
                    MessageBox.Show(ex.Message, "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    return;
                }
                btnCom.Text = "关闭串口";
                btnCom.Tag = "1";
                picComStatus.BackgroundImage = Properties.Resources.greenlight;
            }
            else
            {
                try
                {
                    ComDevice.Close();
                }
                catch (Exception ex)
                {
                    MessageBox.Show(ex.Message, "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
                btnCom.Text = "打开串口";
                btnCom.Tag = "0";
                picComStatus.BackgroundImage = Properties.Resources.redlight;
            }
        }

        #region 发送数据
        private void btnSend_Click(object sender, EventArgs e)
        {
            Send();
            if (cbxAutoSend.Checked == true)
            { //自动循环发送
                timerAutoSend.Interval = txtSendDelay.GetInt32Value();
                timerAutoSend.Enabled = true;
            }
            else
            {
                timerAutoSend.Enabled = false;
            }
        }

        private void timerAutoSend_Tick(object sender, EventArgs e)
        {
            Send();
        }

        private void cbxAutoSend_CheckedChanged(object sender, EventArgs e)
        {
            if (cbxAutoSend.Checked == false)
            {
                timerAutoSend.Enabled = false;
            }
        }
        //清空发送区
        private void btnClearS_Click(object sender, EventArgs e)
        {
            txtSend.Text = "";
        }

        /// <summary>
        /// 发送数据
        /// </summary>
        private void Send()
        {
            if (txtSend.Text.Length > 0)
            {
                if (ComDevice.IsOpen == true)
                {
                    byte[] SendBytes = null;
                    string SendData = txtSend.Text;
                    if (cbxHexS.Checked == true)
                    { //16进制发送
                        try
                        {
                            //剔除所有空格
                            SendData = SendData.Replace(" ", "");
                            if (SendData.Length % 2 == 1)
                            {//奇数个字符
                                SendData = SendData.Remove(SendData.Length - 1, 1);//去除末位字符
                            }
                            List<string> SendDataList = new List<string>();
                            for (int i = 0; i < SendData.Length; i = i   2)
                            {
                                SendDataList.Add(SendData.Substring(i, 2));
                            }
                            SendBytes = new byte[SendDataList.Count];
                            for (int j = 0; j < SendBytes.Length; j  )
                            {
                                SendBytes[j] = (byte)(Convert.ToInt32(SendDataList[j], 16));
                            }
                        }
                        catch
                        {
                            timerAutoSend.Enabled = false;
                            MessageBox.Show("请输入正确的16进制数据!", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                        }
                    }
                    else
                    {
                        if (cbxN.Checked == true)
                        {
                            SendData  = "\n";
                        }
                        SendBytes = System.Text.Encoding.Default.GetBytes(SendData);
                    }
                    ComDevice.Write(SendBytes, 0, SendBytes.Length);//发送数据
                    lblSCount.Text = (Convert.ToInt32(lblSCount.Text)   SendBytes.Length).ToString();
                }
                else
                {
                    timerAutoSend.Enabled = false;
                    MessageBox.Show("请打开串口!", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
            }
            else
            {
                timerAutoSend.Enabled = false;
                MessageBox.Show("请输入要发送的数据!", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }
        #endregion

        #region 接收数据
        private void cbxAllowR_CheckedChanged(object sender, EventArgs e)
        {
            AllowReceive = cbxAllowR.Checked;
        }

        private void ComDevice_DataReceived(object sender, SerialDataReceivedEventArgs e)
        {
            if (AllowReceive == true)
            {
                byte[] ReDatas = new byte[ComDevice.BytesToRead];//返回命令包
                ComDevice.Read(ReDatas, 0, ReDatas.Length);//读取数据
                if (cbxHexR.Checked == true)
                { //16进制显示
                    StringBuilder sb = new StringBuilder();
                    for (int i = 0; i < ReDatas.Length; i  )
                    {
                        sb.AppendFormat("{0:x2}"   " ", ReDatas[i]);
                    }
                    UpdateRecevie(sb.ToString().ToUpper());
                }
                else
                {//ASCII码显示
                    UpdateRecevie(System.Text.Encoding.Default.GetString(ReDatas));
                }
                UpdateReceiveCount(ReDatas.Length);
            }
            else
            {
                ComDevice.DiscardInBuffer();
            }
        }
        //清空接收区
        private void btnClearR_Click(object sender, EventArgs e)
        {
            txtReceive.Text = "";
        }
        #endregion

        #region UI更新
        public delegate void UpdateString(object NewData);
        public void UpdateRecevie(object NewData)
        {
            if (this.InvokeRequired)//等待异步
            {
                UpdateString _myInvoke = new UpdateString(UpdateRecevie);
                this.Invoke(_myInvoke, new object[] { NewData });
            }
            else
            {
                txtReceive.AppendText(NewData.ToString());
                txtReceive.SelectionStart = txtReceive.Text.Length - 1;
                txtReceive.ScrollToCaret();
            }
        }
        public void UpdateReceiveCount(object NewCount)
        {
            if (this.InvokeRequired)//等待异步
            {
                UpdateString _myInvoke = new UpdateString(UpdateReceiveCount);
                this.Invoke(_myInvoke, new object[] { NewCount });
            }
            else
            {
                lblRCount.Text = (Convert.ToInt32(lblRCount.Text)   Convert.ToInt32(NewCount)).ToString();
            }
        }
        #endregion

        #region 其他
        private void TMenu_Byte_Click(object sender, EventArgs e)
        {
            BCWin.Show(); 
        }

        private void TMenu_C_Click(object sender, EventArgs e)
        {
            Cwin.Show();
        }
        private void TMenu_AboutMe_Click(object sender, EventArgs e)
        {
            new SubWin.AboutMe().ShowDialog();
        }
        private void btnClearCount_Click(object sender, EventArgs e)
        {
            lblRCount.Text = "0";
            lblSCount.Text = "0";
        }
        #endregion
        
    }
}