基于C#的串口助手,VS2022最新教程

时间:2024-10-01 13:07:41

  大家好,给大家分享一个本人集合了****各方的代码做成了一个基于C#的串口助手,学了两三天,还是挺不错的,该有的功能都有,给大家看下界面。

设计的思路也很简单

获取串口号:这边使用定时器来获取,可以达到实时更新串口号的效果,点击选择串口定时器就关闭, 关闭串口就会继续开始获取串口号。

自动发送功能,再增加了一个定时器来搞。

其它的就大同小异了。

字符串转16   字节转16进制的都给大家写好了,可以直接拿来用的C#串口助手,界面美观,注释多VS2022开发资源-****文库

想要工程源码的我也给大家上传到

下面来给大家分享源码。这里就不一一教大家去做了,可以写好界面直接参考代码

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


namespace WindowsFormsApp1
{
    public partial class Form1 : Form
    {
        private DateTime current_time = new DateTime();
        public Form1()
        {
            InitializeComponent();
            //Thread autoSendThread = new Thread(AutoSendMethod);
            timer1.Start();
            //设置ComboBox框的初始值
            Band_comboBox.SelectedIndex = 7;
            Data_comboBox.SelectedIndex = 3;
            Stop_comboBox.SelectedIndex = 1;
            Check_comboBox.SelectedIndex = 0;
        }
        private void timer1_Tick(object sender, EventArgs e)
        {
            string[] ports = SerialPort.GetPortNames();
            Sp_comboBox.Items.Clear();
            foreach (string port in ports)
            {
                Sp_comboBox.Items.Add(port);
            }
            Sp_comboBox.SelectedIndex = 0;
        }

        private void openSp_Btn_Click(object sender, EventArgs e)
        {
            if (openSp_Btn.Tag == "1")
            {
                if (!serialPort1.IsOpen)
                {
                    serialPort1.PortName = Sp_comboBox.Text;
                    serialPort1.BaudRate = int.Parse(Band_comboBox.Text);
                    //数据位
                    serialPort1.DataBits = int.Parse(Data_comboBox.Text);
                    //停止位
                    switch (Stop_comboBox.Text)
                    {
                        case "0":
                            serialPort1.StopBits = StopBits.None;
                            break;
                        case "1":
                            serialPort1.StopBits = StopBits.One;
                            break;
                        case "2":
                            serialPort1.StopBits = StopBits.Two;
                            break;
                    }
                    switch (Check_comboBox.Text)
                    {
                        case "0":
                            serialPort1.Parity = Parity.None;
                            break;
                        case "1":
                            serialPort1.Parity = Parity.Odd;
                            break;
                        case "2":
                            serialPort1.Parity = Parity.Even;
                            break;
                    }
                    try
                    {
                        //禁止操作组件
                        Band_comboBox.Enabled = false;
                        Sp_comboBox.Enabled = false;
                        Data_comboBox.Enabled = false;
                        Stop_comboBox.Enabled = false;
                        Check_comboBox.Enabled = false;
                        serialPort1.Open(); //设置完参数后打开串口
                        openSp_Btn.Tag = "0";
                        timer1.Stop();
                        openSp_Btn.Text = "关闭串口";
                    }
                    catch (Exception ex)
                    {
                        MessageBox.Show("串口打开失败1!" + ex.Message);
                    }
                    //serialPort1.DataReceived += new SerialDataReceivedEventHandler(SerialDataReceive);  //打开串口后绑定数据接收
                }
            }
            else
            {
                try
                {
                    Sp_comboBox.Enabled = true;
                    Band_comboBox.Enabled = true;
                    Data_comboBox.Enabled = true;
                    Stop_comboBox.Enabled = true;
                    Check_comboBox.Enabled = true;
                    //.Enabled = true;
                    serialPort1.DiscardInBuffer();  //清除缓冲区的数据
                    serialPort1.Close();
                    openSp_Btn.Text = "打开串口";   //更改Close按钮文本内容
                    openSp_Btn.Tag = "1";
                    timer1.Start();         //允许操作组件
                }
                catch
                {
                    MessageBox.Show("串口打开失败!");
                }
            }
        }
        //接受消息
        private void serialPort1_DataReceived(object sender, SerialDataReceivedEventArgs e)
        {
            int len = serialPort1.BytesToRead;//获取可以读取的字节数
            byte[] buff = new byte[len];//创建缓存数据数组
            serialPort1.Read(buff, 0, len);//把数据读取到buff数组
            string str = Encoding.Default.GetString(buff);//Byte值根据ASCII码表转为 String
            current_time = System.DateTime.Now;
            Invoke((new Action(() => //C# 3.0以后代替委托的新方法
            {
                if (HexShow_checkBox.Checked)
                {
                    if (ShowTime_checkBox.Checked) 
                        Show_richTextBox.AppendText("[" + current_time.ToString("yyyy-MM-dd HH:mm:ss") +
                            "]收→" + byteToHexStr(buff) + "\r\n");
                    else
                            Show_richTextBox.AppendText(byteToHexStr(buff));
                    }
                else
                {
                    if (ShowTime_checkBox.Checked)
                        Show_richTextBox.AppendText("[" + current_time.ToString("yyyy-MM-dd HH:mm:ss") +
                            "]收→" + str + "\r\n");//对话框追加显示数据
                    else
                        Show_richTextBox.AppendText(str);
                }
            })));
        }
        //清屏
        private void Clear_Btn_Click(object sender, EventArgs e)
        {
            Show_richTextBox.Clear();
        }
        //字节转16进制
        public static string byteToHexStr(byte[] bytes)
        {
            string returnStr = "";
            try
            {
                if (bytes != null)
                {
                    for (int i = 0; i < bytes.Length; i++)
                    {
                        returnStr += bytes[i].ToString("X2");
                        returnStr += " ";//两个16进制用空格隔开,方便看数据
                    }
                }
                return returnStr;
            }
            catch (Exception)
            {
                return returnStr;
            }
        }
        //字符串转字节
        private static byte[] strToToHexByte(String hexString)
        {
            int i;
            hexString = hexString.Replace(" ", "");//清除空格
            if ((hexString.Length % 2) != 0)//奇数个
            {
                byte[] returnBytes = new byte[(hexString.Length + 1) / 2];
                try
                {
                    for (i = 0; i < (hexString.Length - 1) / 2; i++)
                    {
                        returnBytes[i] = Convert.ToByte(hexString.Substring(i * 2, 2), 16);
                    }
                    returnBytes[returnBytes.Length - 1] = Convert.ToByte(hexString.Substring(hexString.Length - 1, 1).PadLeft(2, '0'), 16);
                }
                catch
                {
                    MessageBox.Show("含有非16进制字符", "提示");
                    return null;
                }
                return returnBytes;
            }
            else
            {
                byte[] returnBytes = new byte[(hexString.Length) / 2];
                try
                {
                    for (i = 0; i < returnBytes.Length; i++)
                    {
                        returnBytes[i] = Convert.ToByte(hexString.Substring(i * 2, 2), 16);
                    }
                }
                catch
                {
                    MessageBox.Show("含有非16进制字符", "提示");
                    return null;
                }
                return returnBytes;
            }
        }
        //发送消息
        private void Send_Btn_Click(object sender, EventArgs e)
        {
            sendData();
        }

        private void timer2_Tick(object sender, EventArgs e)
        {
            sendData();
        }

        private void AutoSend_checkBox_CheckedChanged(object sender, EventArgs e)
        {
            if (AutoSend_checkBox.Checked == true)
            {
                int time;
                if (int.TryParse(AutoTime_textBox.Text, out time))
                {
                    timer2.Interval = time;
                    timer2.Start();
                }
                else
                {
                    // 转换失败,文本框中的内容不是有效的整数,可以进行错误处理
                    MessageBox.Show("请输入有效的整数作为时间值。");
                    AutoSend_checkBox.Checked = false;
                }
            }
            else
            {
                timer2.Stop();
            }
        }
        public void sendData()
        {
            current_time = System.DateTime.Now;
            String Str = Send_textBox.Text.ToString();//获取发送文本框里面的数据
            //if (Rn_checkBox.Checked)
            //    Str += "\r\n";
            try
            {
                if (Str.Length > 0)
                {
                    if (!HexSend_checkBox.Checked)
                    {
                        if(Rn_checkBox.Checked)
                            serialPort1.Write(Str + "\r\n");//串口发送数据
                        else
                            serialPort1.Write(Str);
                        if (ShowTime_checkBox.Checked)
                            Show_richTextBox.AppendText("[" + current_time.ToString("yyyy-MM-dd HH:mm:ss") +
                                "]发→" + Str + "\r\n");
                        else
                            Show_richTextBox.AppendText("发→" + Str);
                    }
                    else
                    { 
                        byte[] byt = strToToHexByte(Str);
                        serialPort1.Write(byt, 0, byt.Length);
                        string hexString = BitConverter.ToString(byt).Replace("-", " ");
                        if (!ShowTime_checkBox.Checked)
                             Show_richTextBox.AppendText("发→" + hexString + Environment.NewLine);
                        else
                             Show_richTextBox.AppendText("[" + current_time.ToString("yyyy-MM-dd HH:mm:ss") +
                                "]发→" + hexString + Environment.NewLine + "\r\n");
                    }
                }
            }
            catch (Exception) { }
        }

        private void Sp_comboBox_SelectedIndexChanged(object sender, EventArgs e)
        {
            timer1.Stop();
        }
    }
}