C#串口助手源码,可以记录发送和接收内容

C#串口助手源码,可以记录发送和接收内容

如图

请添加图片描述

/*
 *待改进:
 *不支持中文发送接收
 */

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;

namespace SerialModbus
{
    public partial class Form1 : Form
    {
        
        int RxCount = 0;//接收计数
        int TxCount = 0;//发送计数
        private StringBuilder Rxbuilder = new StringBuilder();
        private StringBuilder Txbuilder = new StringBuilder();
        //int dsjs = 0;//定时发送次数
        //short kongzhi = 0;
      
        public Form1()
        {
            InitializeComponent();
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            int a = 0,i=0;
            string[] SysSerialName = System.IO.Ports.SerialPort.GetPortNames();//获取已有的端口
            a = SysSerialName.Length;

            //comboBox1_SerialPortn.SelectedIndex  = 0;
            comboBox2_BaudRate.SelectedIndex = 5;
            comboBox3_DataBits.SelectedIndex = 0;
            comboBox4_StopBits.SelectedIndex = 0;
            comboBox5_CRCBits.SelectedIndex = 0;
            pictureBox_SerialState.BackColor = Color.Red;
            Control.CheckForIllegalCrossThreadCalls = false;//屏蔽非法跨线程调用将始终引发异常
            SerialPort1.DataReceived += new SerialDataReceivedEventHandler(SerialPort1_DataReceived);//添加串口接收DataReceived事件
            if (a < 0)
            {
                MessageBox.Show("没有找到端口!", "警告");
            }
            else
            {
                for (; i < a; i++)
                {
                    if (Convert.ToInt32(SysSerialName[i].Remove(0, 3)) > 6)//从零开始删除3个字符,并转换成整形
                    {
                        comboBox1_SerialPortn.Items .Add (SysSerialName[i]);
                    }
           
                }
                i = 0;//将i清零
            #region 自动打开串口
            go: for (; i < a + 6; i++)
                    //  自动打开端口
                    try
                    {
                        if (SerialPort1.IsOpen == true)
                        {
                            break;
                        }
                        else
                        {
                            comboBox1_SerialPortn.SelectedIndex =i;
                            // MessageBox.Show(i.ToString ());
                            SerialPort1.PortName = comboBox1_SerialPortn.Text;
                            //MessageBox.Show(i.ToString());
                            SerialPort1.Open();
                            if (SerialPort1.IsOpen == true)
                            {
                                comboBox1_SerialPortn.SelectedIndex = i;
                                //Label6.Text = "端口已打开";
                                pictureBox_SerialState.BackColor = Color.Green;
                                button_OpenSerial.Text = "关闭端口";
                            }
                        }
                    }
                    catch (IOException)//串口不存在异常
                    {
                        i++;
                        goto go;

                    }
                    catch (UnauthorizedAccessException)//串口资源占用异常
                    {
                        i++;
                        goto go;
                    }
                    catch (InvalidOperationException)//串口打开后,不能在赋值端口异常
                    {
                        i++;
                        goto go;
                    }
                #endregion
            if (SerialPort1.IsOpen == false)
            {
                comboBox1_SerialPortn.SelectedIndex = 0;
            }

            this.button_Tx.Select(); //开始运行程序时,让发送区被选择,激活控件



          }
        }

        private void FaSong()//发送子函数
        {
            int Data = 0;
            string str = textBox_TxInput.Text;

            foreach (char ch in str)//取字符长度
            {
                Data++;
            }
            //MessageBox.Show(Data.ToString ());
            if (SerialPort1.IsOpen == false)
            {
                //CheckBox1.Checked = false;//定时发送状态选钮
                MessageBox.Show("端口未打开,请打开端口!", "提示");
            }
            else
            {
                //    ------------------------------------发送十六进制数---------------------------------------------

                if (radioButton_TxHEX.Checked == true)//发送十六进制数
                {
                    //if (Data % 2 == 0)
                    {
                        byte[] data = Algorithm._16ToBtyes(textBox_TxInput.Text);
                        SerialPort1.Write(data, 0, data.Length);
                        TxCount = TxCount + data.Length;//发送计数
                        this.textBox_TxDisplay.AppendText(Algorithm.BytesTo16(data, Enum16进制隔离符.空格) + "\r\n");
                    }
                   // else
                   //     MessageBox.Show("十六进制错误,请您检查!", "提示", MessageBoxButtons.OK, MessageBoxIcon.Error);
                }

                //    Else '------------------------------------发送字符串----------------------------------
                else
                {
                    if (textBox_TxInput.Text == "")
                    {
                        // CheckBox1.Checked = false; //定时发送状态选钮
                        MessageBox.Show("请在发送数据框内输入数据!", "提示");
                    }
                    else
                    {
                        //SerialPort1.Write(Textfasong.Text);
                        byte[] bt = Algorithm.StringToBytes(textBox_TxInput.Text, false);
                        SerialPort1.Write(bt, 0, bt.Length);
                        TxCount += 1; //发送计数
                        this.textBox_TxDisplay.AppendText(Algorithm.BytesToString(bt, Enum16进制隔离符.空格) +"\r\n");
                    }
                }
            }
            textBox_TxCont.Text = TxCount.ToString();
        }

        private void comboBox1_SerialPortn_SelectedIndexChanged(object sender, EventArgs e)
        {
            try
            {
                if (SerialPort1.IsOpen == true)//判断端口是不是打开
                {
                    //while (Listening); 
                    SerialPort1.Close();
                }
                SerialPort1.PortName = comboBox1_SerialPortn.Text; //设置端口号
                SerialPort1.Open();
                if (SerialPort1.IsOpen == true)
                {
                    //Label6.Text = "端口已打开";
                    pictureBox_SerialState.BackColor = Color.Green;
                    button_OpenSerial.Text = "关闭端口";
                }
            }
            catch (IOException)//串口不存在异常
            {

                //Label6.Text = "端口未打开";
                pictureBox_SerialState.BackColor = Color.Red;
                button_OpenSerial.Text = "打开端口";
            }
            catch (UnauthorizedAccessException)//串口资源占用异常
            {
                //Label6.Text = "端口未打开";
                pictureBox_SerialState.BackColor = Color.Red;
                button_OpenSerial.Text = "打开端口";
            }
        }

        private void button_OpenSerial_Click(object sender, EventArgs e)
        {
            try
            {
                if (button_OpenSerial.Text == "关闭端口")
                {
                    //while (Listening) ; 
                    SerialPort1.Close();
                    //Label6.Text = "端口未打开";
                    pictureBox_SerialState.BackColor = Color.Red;
                    button_OpenSerial.Text = "打开端口";
                }
                else
                {
                    SerialPort1.Open();
                    if (SerialPort1.IsOpen == true)
                    {
                        //Label6.Text = "端口已打开";
                        pictureBox_SerialState.BackColor = Color.Green;
                        button_OpenSerial.Text = "关闭端口";
                    }
                    else
                    {
                        //Label6.Text = "端口未打开";
                        pictureBox_SerialState.BackColor = Color.Red;
                        button_OpenSerial.Text = "打开端口";
                        MessageBox.Show("端口不存在或被占用!", "提示");
                    }
                }
            }
            catch (IOException)//串口不存在异常
            {

                if (SerialPort1.IsOpen == true)
                {
                    //Label6.Text = "端口已打开";
                    pictureBox_SerialState.BackColor = Color.Green;
                    button_OpenSerial.Text = "关闭端口";
                }
                else
                {
                    //Label6.Text = "端口未打开";
                    pictureBox_SerialState.BackColor = Color.Red;
                    button_OpenSerial.Text = "打开端口";
                    MessageBox.Show("端口不存在或被占用!", "提示");
                }

            }
            catch (UnauthorizedAccessException)//串口资源占用异常
            {

                if (SerialPort1.IsOpen == true)
                {
                    //Label6.Text = "端口已打开";
                    pictureBox_SerialState.BackColor = Color.Green;
                    button_OpenSerial.Text = "关闭端口";
                }
                else
                {
                    //Label6.Text = "端口未打开";
                    pictureBox_SerialState.BackColor = Color.Red;
                    button_OpenSerial.Text = "打开端口";
                    MessageBox.Show("端口不存在或被占用!", "提示");
                }
            }
            catch (InvalidOperationException)//串口打开后,不能在赋值端口异常
            {

                if (SerialPort1.IsOpen == true)
                {
                    //Label6.Text = "端口已打开";
                    pictureBox_SerialState.BackColor = Color.Green;
                    button_OpenSerial.Text = "关闭端口";
                }
                else
                {
                    //Label6.Text = "端口未打开";
                    pictureBox_SerialState.BackColor = Color.Red;
                    button_OpenSerial.Text = "打开端口";
                    MessageBox.Show("端口不存在或被占用!", "提示");
                }
            }     
        }
        private void SerialPort1_DataReceived(object sender, System.IO.Ports.SerialDataReceivedEventArgs e)//接收数据事件
        {
            #region 显示数据
           // if (myClosing) return; //关闭串口标志,点击关闭串口后,立即停止显示
            try
            {
               // Listening = true;//正在接收标志,此位为false才能关闭串口 否则容易卡死
                int n = SerialPort1.BytesToRead;
                byte[] buf = new byte[n];
                RxCount += n;
                SerialPort1.Read(buf, 0, n);
                Rxbuilder.Clear();
                if (radioButton_RxTxt.Checked == true)
                {
                    // Invoke(new EventHandler(DisplayText));//private void DisplayText(object sender, EventArgs e){  } //另一种显示方法,自定义显示函数。
                    Invoke((EventHandler)(delegate
                    {
                        //Rxbuilder.Append(Encoding.Default.GetBytes(str));// 字符串转ASCII
                        Rxbuilder.Append(Encoding.ASCII.GetString(buf)+"\r\n");//ASCII转字符串 
                    }));
                }
                else // public static string BytesTo16(byte[] bytes, Enum16进制隔离符 enum16)
                {
                    //for (i = 0; i < n; i++) 
                    Rxbuilder.Append(Algorithm.BytesTo16(buf, Enum16进制隔离符.空格));         
                }
                this.textBox_RxDisplay.AppendText(Rxbuilder.ToString());
            }
            finally
            {
               // Listening = false;
            }
            #endregion    
            textBox_RxCont.Text = RxCount.ToString();
        }






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

        private void button4_Click(object sender, EventArgs e)
        {
            textBox_RxDisplay.Text = "";
        }
        private void button_Tx_Click(object sender, EventArgs e)
        {
            FaSong();
        }

        private void comboBox2_BaudRate_SelectedIndexChanged(object sender, EventArgs e)
        {
            SerialPort1.BaudRate = Convert.ToInt32(comboBox2_BaudRate.Text);//设置波特率
        }

        private void comboBox3_DataBits_SelectedIndexChanged(object sender, EventArgs e)
        {
            SerialPort1.DataBits = Convert.ToInt32(comboBox3_DataBits.Text);//设置数据位
        }

        private void comboBox4_StopBits_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (comboBox4_StopBits.Text == "1")
                SerialPort1.StopBits = System.IO.Ports.StopBits.One;
            else if (comboBox4_StopBits.Text == "2")
                SerialPort1.StopBits = System.IO.Ports.StopBits.Two;
        }

        private void comboBox5_CRCBits_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (comboBox5_CRCBits.Text == "EVEN")
                SerialPort1.Parity = System.IO.Ports.Parity.Even; //设置奇偶校验
            else if (comboBox5_CRCBits.Text == "NONE")
                SerialPort1.Parity = System.IO.Ports.Parity.None;
            else if (comboBox5_CRCBits.Text == "0DD")
                SerialPort1.Parity = System.IO.Ports.Parity.Odd;
        }







    }
}

源码下载:https://download.csdn.net/download/weixin_43330894/86406546

  • 0
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值