在好例子网,分享、交流、成长!
您当前所在位置:首页C# 开发实例桌面应用界面/GUI → C#串口助手源码(向串口发送数据以及接收串口数据,支持发送文件)

C#串口助手源码(向串口发送数据以及接收串口数据,支持发送文件)

桌面应用界面/GUI

下载此实例
  • 开发语言:C#
  • 实例大小:0.14M
  • 下载次数:126
  • 浏览次数:967
  • 发布时间:2019-09-21
  • 实例类别:桌面应用界面/GUI
  • 发 布 人:fengyuzhou
  • 文件格式:.zip
  • 所需积分:5
 相关标签: 串口助手 助手 串口 C#

实例介绍

【实例简介】

【实例截图】

from clipboard

【核心代码】

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

using System.IO.Ports;
using System.Text.RegularExpressions;
using System.Runtime.InteropServices;
using System.IO;
using System.Threading;

namespace WindowsFormsApplication2
{
    public partial class Form1 : Form
    {
        public int R_cnt = 0;//接收计数
        public int S_cnt = 0;//发送计数
        public bool Sending_Flag = false;//正在发送文件标志
        public string str_Rec;//用于数据接收显示时缓存
        /// <summary>
        /// 文件
        /// </summary>
        private static FileStream fs = null;
        private static long index = 0;
        private static long blockCount;
        private static int size = 4095;//4095 1=2M
        string filename;//文件名
        ///
        
        /// <summary>
        /// 委托用于接收显示
        /// </summary>
        /// <param name="InputBuf"></param>
        //声明了一个delegate 类型
        public delegate void Displaydelegate(byte[] InputBuf);
        //声明了一个delegate 对象
        public Displaydelegate disp_delegate;
        //将串口接收到的数据显示到textBox1上
        public void DispUI(byte[] InputBuf)
        {
            ASCIIEncoding encoding = new ASCIIEncoding();
            if (display16.Checked == true)
            {
                foreach (byte b in InputBuf)
                {
                    //将数值转换成16进制数并追加一个空格并显示到textBox1上
                    receivebuf.AppendText(b.ToString("X2")   " ");
                }
            }
            else
            {
                //直接将数值转换成字符串并显示并显示到textBox1上
                receivebuf.AppendText(System.Text.Encoding.Default.GetString(InputBuf));
            }
        }

        //声明了一个delegate 类型
        public delegate void StopSenddelegate();
        public void DispStopSend()
        {
            SendFile.Enabled = true;// 
            send.Enabled = true;//"发送"按键使能
            timersend.Enabled = true;//失效       
        }

        //声明了一个delegate1 类型
        public delegate void SendOkdelegate();
        public void DispSendOk()
        {
            SendFile.Enabled = true;//
            send.Enabled = true;//"发送"按键使能
            timersend.Enabled = true;//失效  
            sendprogressBar.Step = 100;//设置progressBar1的增值为1
            sendprogressBar.PerformStep();//使用PerformStep方法按Step值递增 
            sendpercentage.Text = "100%";        
        }

        //声明了一个delegate1 类型
        public delegate void Sendingdelegate();
        public void DispSending()
        {
            sendprogressBar.Step = (int)(size  * 100 / fs.Length);//设置progressBar1的增值为
            sendprogressBar.PerformStep();//使用PerformStep方法按Step值递增 
            sendpercentage.Text = ((int)((size * index) * 100 / fs.Length)).ToString()   '%';
        }

        /// <summary>
        /// 线程实现函数
        /// </summary>
        //thread开启线程要求:该方法参数只能有一个,且是object类型
        public void sendfile()
        {
            fs = new FileStream(filename, FileMode.Open, FileAccess.Read);
            blockCount = (fs.Length - 1) / size   1;
            for (;;)
            {
                if (Sending_Flag == false)//正在发送文件标志
                {
                    //创建一个delegate 对象
                    StopSenddelegate StopSenddelegate = new StopSenddelegate(DispStopSend);
                    Invoke(StopSenddelegate);// 委托
                    break;
                }
                if (index == blockCount - 1)//判断是否最后一次发送数据块
                {
                    byte[] bArr = new byte[fs.Length - (size * index)   1];
                    fs.Read(bArr, 1, bArr.Length - 1);
                    index = 0;
                    serialPort1.Write(bArr, 0, bArr.Length);
                    //创建一个delegate 对象
                    SendOkdelegate SendOkdelegate = new SendOkdelegate(DispSendOk);
                    Invoke(SendOkdelegate);// 委托
                    S_cnt  = bArr.Length;//发送计数
                    break;
                }
                else
                {
                    byte[] bArr = new byte[size   1];//创建一个4Kb的byte[]
                    fs.Read(bArr, 1, size);//每次读入4Kb
                    index  ;
                    serialPort1.Write(bArr, 0, bArr.Length);//每次发送4Kb
                    //创建一个delegate 对象
                    Sendingdelegate Sendingdelegate = new Sendingdelegate(DispSending);
                    Invoke(Sendingdelegate);
                    S_cnt  = bArr.Length;//发送计数
                }
            }
        }
        /// <summary>
        /// 
        /// </summary>
        public Form1()
        {
            //创建一个delegate 对象
            disp_delegate = new Displaydelegate(DispUI);
            InitializeComponent();
        }
        /// <summary>
        /// 打开软件处理函数
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void Form1_Load(object sender, EventArgs e)
        {
            try
            {
                int i;
                ///开定时器2
                timer2.Enabled = true;
                timer2.Interval = 500;  //定时器时间间隔
                timer2.Start();   //定时器开始工作
                ///
                //获取端口名字 使用前需要添加 using System.IO.Ports;
                string[] PortName = SerialPort.GetPortNames();
                Array.Sort(PortName);//给端口名称排序
                com.Items.Clear();
                baudrate.Text = "115200";
                stopbit.Text = "1";
                databit.Text = "8";
                check.Text = "无";
                comstats.Text = "Close";
                sendpercentage.Text = "0%";
                sendprogressBar.Value = 0;//设置进度条的初始值 
                sendprogressBar.Minimum = 0;//设置progressBar1控件的Minimum值为0 
                sendprogressBar.Maximum = 100;//设置progressBar1的Maximum值为500 
                S_cnt = 0;//发送计数 
                R_cnt = 0;//接收计数 
                lblRCount.Text = "0";
                lblSCount.Text = "0";
                comstats.Text = "Close";
                //因为存储在comboBox2中的数值都为字符串,所以需要将端口号转换为10进制数值
                ///////////波特率
                serialPort1.BaudRate = Convert.ToInt32(baudrate.Text, 10);
                ///////////停止位
                if (Convert.ToInt32(stopbit.Text, 10) == 1)
                {
                    serialPort1.StopBits = (StopBits)1;
                }
                else if (Convert.ToInt32(stopbit.Text, 10) == 2)
                {
                    serialPort1.StopBits = (StopBits)2;
                }
                else
                {
                    serialPort1.StopBits = (StopBits)3;
                }
                ///////////数据位
                serialPort1.DataBits = Convert.ToInt32(databit.Text, 10);
                ///////////奇偶校验
                if (check.Text.Contains("奇校验"))
                {
                    serialPort1.Parity = (Parity)1;
                }
                else if (check.Text.Contains("偶校验"))
                {
                    serialPort1.Parity = (Parity)2;
                }
                else
                {
                    serialPort1.Parity = (Parity)0;
                }
                ////////////////自动连接
                for ( i = 0; i < PortName.Length; i  )
                {
                    try
                    {
                        com.Items.Add(PortName[i]);//给comboBox1添加选项
                        com.Text = PortName[i];
                        serialPort1.PortName = com.Text;//更改端口名称
                        serialPort1.Open();//打开串口
                        opencom.Enabled = false;//"打开串口"按键失效
                        closecom.Enabled = true;//"关闭串口"按键使能
                        send.Enabled = true;//"发送"按键使能
                        baudrate.Enabled = false;
                        stopbit.Enabled = false;
                        databit.Enabled = false;
                        check.Enabled = false;
                        timersend.Enabled = true;//失效
                        SendFile.Enabled = true;//"发送文件"按键使能
                        OpenFile.Enabled = true;//"打开文件"按键使能
                        comstats.Text="Open"   ' '   com.Text ' '  baudrate.Text   ' '   stopbit.Text   ' '   databit.Text   ' '   check.Text;
                        break;
                    }
                    catch (Exception)
                    {
                        continue;
                    }
                }
                ///////////////
                if(i== PortName.Length)
                {
                    opencom.Enabled = true;//"打开串口"按键使能
                    closecom.Enabled = false;//"关闭串口"按键失效
                    send.Enabled = false;//"发送"按键失效
                    baudrate.Enabled = true;//使能
                    stopbit.Enabled = true;//使能
                    databit.Enabled = true;//使能
                    check.Enabled = true;//使能
                    timersend.Enabled = false;//失效
                    timersend.Checked = false;
                    SendFile.Enabled = false;//"发送文件"按键失效
                    OpenFile.Enabled = false;//"打开文件"按键失效
                } 
            }
            catch (Exception)
            {
                opencom.Enabled = true;//"打开串口"按键使能
                closecom.Enabled = false;//"关闭串口"按键失效
                send.Enabled = false;//"发送"按键失效
                baudrate.Enabled = true;//使能
                stopbit.Enabled = true;//使能
                databit.Enabled = true;//使能
                check.Enabled = true;//使能
                timersend.Enabled = false;//失效
                timersend.Checked = false;
                SendFile.Enabled = false;//"发送文件"按键失效
                OpenFile.Enabled = false;//"打开文件"按键失效
            }
        }
        /// <summary>
        /// 打开串口
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void button1_Click(object sender, EventArgs e)
        {
            try
            {
                serialPort1.PortName = com.Text;//更改端口名称
                //因为存储在comboBox2中的数值都为字符串,所以需要将端口号转换为10进制数值
                ///////////波特率
                serialPort1.BaudRate = Convert.ToInt32(baudrate.Text, 10);
                ////////////停止位
                if (Convert.ToInt32(stopbit.Text, 10) == 1)
                {
                    serialPort1.StopBits = (StopBits)1;
                }
                else if (Convert.ToInt32(stopbit.Text, 10) == 2)
                {
                    serialPort1.StopBits = (StopBits)2;
                }
                else
                {
                    serialPort1.StopBits = (StopBits)3;
                }
                ////////////数据位
                serialPort1.DataBits = Convert.ToInt32(databit.Text, 10);
                ////////////奇偶位
                if (check.Text.Contains("奇校验"))
                {
                    serialPort1.Parity = (Parity)1;
                }
                else if (check.Text.Contains("偶校验"))
                {
                    serialPort1.Parity = (Parity)2;
                }
                else
                {
                    serialPort1.Parity = (Parity)0;
                }
                /////////////
                serialPort1.Open();//打开串口
                opencom.Enabled = false;//"打开串口"按键失效
                closecom.Enabled = true;//"关闭串口"按键使能
                send.Enabled = true;//"发送"按键使能
                baudrate.Enabled = false;
                stopbit.Enabled = false;
                databit.Enabled = false;
                check.Enabled = false;
                timersend.Enabled = true;//失效
                SendFile.Enabled = true;//"发送文件"按键使能
                OpenFile.Enabled = true;//"打开文件"按键使能
                comstats.Text = "Open"   ' '   com.Text   ' '   baudrate.Text   ' '   stopbit.Text   ' '   databit.Text   ' '   check.Text;
                sendpercentage.Text = "0%";
                sendprogressBar.Value = 0;//设置进度条的初始值 
                sendprogressBar.Minimum = 0;//设置progressBar1控件的Minimum值为0 
                sendprogressBar.Maximum = 100;//设置progressBar1的Maximum值为500 
                S_cnt = 0;//发送计数 
                R_cnt = 0;//接收计数 
                lblRCount.Text = "0";
                lblSCount.Text = "0";
            }
            catch (Exception ex)
            {
                MessageBox.Show("端口错误,请检查端口", "错误");
            }
        }
        /// <summary>
        /// 关闭串口
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void button2_Click(object sender, EventArgs e)
        {
            try
            {
                serialPort1.Close();//关闭串口
                opencom.Enabled = true;//"打开串口"按键使能
                closecom.Enabled = false;//"关闭串口"按键失效
                send.Enabled = false;//"发送"按键失效
                baudrate.Enabled = true;//使能
                stopbit.Enabled = true;//使能
                databit.Enabled = true;//使能
                check.Enabled = true;//使能
                timersend.Enabled = false;//失效
                timersend.Checked = false;
                SendFile.Enabled = false;//"发送文件"按键失效
                OpenFile.Enabled = false;//"打开文件"按键失效
                comstats.Text = "Close";
                sendpercentage.Text = "0%";
                sendprogressBar.Value = 0;//设置进度条的初始值 
                sendprogressBar.Minimum = 0;//设置progressBar1控件的Minimum值为0 
                sendprogressBar.Maximum = 100;//设置progressBar1的Maximum值为500 
                S_cnt = 0;//发送计数 
                R_cnt = 0;//接收计数 
                lblRCount.Text = "0";
                lblSCount.Text = "0";
            }
            catch (Exception ex)
            {
             
            }
        }
        /// <summary>
        /// 点击发送按键处理函数
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void button3_Click(object sender, EventArgs e)
        {
            try
            {
                if (sendbuf.Text.Trim() == String.Empty)
                {
                    MessageBox.Show("发送数据不能为空");
                    return;
                }
                if (send16.Checked == true)//选择16进制发送时
                {
                    List<byte> buf = new List<byte>();//填充到这个临时列表中
                    //使用正则表达式获取textBox2中的有效数据
                    MatchCollection mc = Regex.Matches(sendbuf.Text, @"(?i)[\da-f]{2}");
                    //将mc转换为16进制数据并添加到buf列表中
                    foreach (Match m in mc)
                    {
                        byte data = Convert.ToByte(m.Value, 16);
                        buf.Add(data);
                    }
                    ///////////处理最后一位为奇数时
                    if ((sendbuf.Text.Length % 2) != 0)
                    {
                        MatchCollection mc1 = Regex.Matches(sendbuf.Text, @"(?i)[\da-f]{1}");
                        for (int i = 0; i < mc1.Count; i  )
                        {
                            byte data = Convert.ToByte(mc1[i].Groups[0].Value, 16);
                            if (i > (mc1.Count - 2))
                            {
                                buf.Add(data);
                            }
                        }
                    }
                    /////////////    
                    if (sendnewline.Checked == true)//选择发送新行时
                    {
                        buf.Add(0x0d);
                        buf.Add(0x0a);
                    }
                    //将buf列表转换为数组并通过串口发送出去
                    serialPort1.Write(buf.ToArray(), 0, buf.Count);
                    S_cnt  = buf.Count;//发送计数
                }
                else//如果选择字符发送模式
                {
                    if (sendnewline.Checked == true)//选择发送新行时
                    {
                        string res = sendbuf.Text   "\r\n";
                        byte[] byteArray = System.Text.Encoding.Default.GetBytes(res);
                        serialPort1.Write(byteArray, 0, byteArray.Length);
                        S_cnt  = byteArray.Length;//发送计数 
                    }
                    else
                    {
                        byte[] byteArray = System.Text.Encoding.Default.GetBytes(sendbuf.Text);
                        serialPort1.Write(byteArray, 0, byteArray.Length);
                        S_cnt  = byteArray.Length;//发送计数 
                    }
                    
                }
            }
            catch (Exception ex)
            {
                
            }
        }
        /// <summary>
        /// 接收处理函数
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void serialPort1_DataReceived(object sender, SerialDataReceivedEventArgs e)
        {
            int n = serialPort1.BytesToRead;//串口缓存中数据的个数
            Byte[] InputBuf = new Byte[n];
            try
            {
                //读取串口缓存中的数据并存放到InputBuf数组中
                serialPort1.Read(InputBuf, 0, serialPort1.BytesToRead);
                //将当前线程挂起50ms
                System.Threading.Thread.Sleep(50);
                //执行委托
                this.Invoke(disp_delegate, InputBuf);
                R_cnt  = serialPort1.BytesToRead;//接收计数 
            }
            catch (TimeoutException ex)
            {
                MessageBox.Show(ex.ToString());
            }
        }
        /// <summary>
        /// 发送区输入内容判断
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void textBox2_KeyPress(object sender, KeyPressEventArgs e)
        {
            try
            {
                if (send16.Checked == true)//选择16进制发送时
                {
                    if (
                            (
                                ((e.KeyChar) >= '0') &&
                                ((e.KeyChar) <= '9')
                            )
                        || (
                                ((e.KeyChar) >= 'a') &&
                                ((e.KeyChar) <= 'f')
                           )
                        || (
                                ((e.KeyChar) >= 'A') &&
                                ((e.KeyChar) <= 'F')
                           )
                        || ((e.KeyChar) == '\b')
                       )
                    {

                    }
                    else
                    {
                        MessageBox.Show("请输出正确的格式 0-9 a-f A-F例如01 06 0a");
                    }
                    e.Handled = "0123456789ABCDEF".IndexOf(char.ToUpper(e.KeyChar)) < 0;
                }
            }
            catch (Exception ex)
            {
               
            }

        }
        /// <summary>
        /// 清空接收区的内容
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void button5_Click(object sender, EventArgs e)
        {
            try
            {
                receivebuf.Clear();
            }
            catch (Exception ex)
            {
               
            }
        }
        /// <summary>
        /// 清空发送区的内容
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void button4_Click(object sender, EventArgs e)
        {
            try
            {
                sendbuf.Clear();
                sendprogressBar.Value = 0;//设置进度条的初始值 
                sendprogressBar.Minimum = 0;//设置progressBar1控件的Minimum值为0 
                sendprogressBar.Maximum = 100;//设置progressBar1的Maximum值为500 
                sendpercentage.Text = "0%";
            }
            catch (Exception ex)
            {
                
            }
        }
        /// <summary>
        /// 点击串口下拉框
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void com_Click(object sender, EventArgs e)
        {
            try
            {
                //获取端口名字 使用前需要添加 using System.IO.Ports;
                string[] PortName = SerialPort.GetPortNames();
                Array.Sort(PortName);//给端口名称排序[]
                com.Items.Clear();
                if (serialPort1.IsOpen)
                {
                    serialPort1.Close();
                    opencom.Enabled = true;//"打开串口"按键使能
                    closecom.Enabled = false;//"关闭串口"按键失效
                    send.Enabled = false;//"发送"按键失效
                    baudrate.Enabled = true;//使能
                    stopbit.Enabled = true;//使能
                    databit.Enabled = true;//使能
                    check.Enabled = true;//使能
                    timersend.Enabled = false;//失效
                    timersend.Checked = false;
                    SendFile.Enabled = false;//"发送文件"按键失效
                    OpenFile.Enabled = false;//"打开文件"按键失效
                }
                for (int i = 0; i < PortName.Length; i  )
                {
                    com.Items.Add(PortName[i]);//给comboBox1添加选项
                }
            }
            catch (Exception ex)
            {
               
            }
        }
        /// <summary>
        /// 接收背景颜色改变
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void receivedisplaycolor_CheckedChanged(object sender, EventArgs e)
        {
            try
            {
                if (receivedisplaycolor.Checked == true)
                {

                    this.receivebuf.BackColor = System.Drawing.Color.White;
                    this.receivebuf.ForeColor = System.Drawing.Color.Black;
                }
                else
                {
                    this.receivebuf.BackColor = System.Drawing.Color.Black;
                    this.receivebuf.ForeColor = System.Drawing.Color.LawnGreen;
                }
            }
            catch (Exception ex)
            {
               
            }
        }
        /// <summary>
        /// 保存窗口函数
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void savefile_Click(object sender, EventArgs e)
        {
            try
            {
                string name = this.receivebuf.Text; //文件名
                string content = this.receivebuf.Text; //文件内容
                string path = string.Empty; //文件路径
                if (receivebuf.Text.Trim() == String.Empty)//为空
                {
                    MessageBox.Show("数据缓冲为空");
                    return;
                }
                SaveFileDialog save = new SaveFileDialog();
                if (save.ShowDialog() == DialogResult.OK)
                {
                    path = save.FileName;
                    path = path   ".txt";
                }
                if (path != string.Empty)
                {
                    using (System.IO.FileStream file = new System.IO.FileStream(path, System.IO.FileMode.Create, System.IO.FileAccess.Write))
                    {
                        using (System.IO.TextWriter text = new System.IO.StreamWriter(file, System.Text.Encoding.Default))
                        {
                            text.Write(content);
                        }
                    }
                }
            }
            catch (Exception ex)
            {
               
            }
        }
        /// <summary>
        /// 接收显示格式
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void display16_CheckedChanged(object sender, EventArgs e)
        {
            if (display16.Checked == true)
            {
                str_Rec= receivebuf.Text;
                byte[] byteArray = System.Text.Encoding.ASCII.GetBytes(receivebuf.Text);
                string hexOutput = " ";
                for(int i=0;i< byteArray.Length;i  )
                {
                    hexOutput  = byteArray[i].ToString("X2")   " ";

                }
                receivebuf.Text = hexOutput;
            }
            else
            {
                receivebuf.Text = str_Rec;
            }
        }

        private void timer1_Tick(object sender, EventArgs e)
        {
            try
            {
                if (sendbuf.Text.Trim() == String.Empty)//为空
                {
                    return;
                }
                if (send16.Checked == true)//选择16进制发送时
                {
                    List<byte> buf = new List<byte>();//填充到这个临时列表中
                                                        //使用正则表达式获取textBox2中的有效数据
                    MatchCollection mc = Regex.Matches(sendbuf.Text, @"(?i)[\da-f]{2}");
                    //将mc转换为16进制数据并添加到buf列表中
                    foreach (Match m in mc)
                    {
                        byte data = Convert.ToByte(m.Value, 16);
                        buf.Add(data);
                    }
                    ///////////处理最后一位为奇数时
                    if ((sendbuf.Text.Length % 2) != 0)
                    {
                        MatchCollection mc1 = Regex.Matches(sendbuf.Text, @"(?i)[\da-f]{1}");
                        for (int i = 0; i < mc1.Count; i  )
                        {
                            byte data = Convert.ToByte(mc1[i].Groups[0].Value, 16);
                            if (i > (mc1.Count - 2))
                            {
                                buf.Add(data);
                            }
                        }
                    }
                    /////////////    
                    if (sendnewline.Checked == true)//选择发送新行时
                    {
                        buf.Add(0x0d);
                        buf.Add(0x0a);
                    }
                    //将buf列表转换为数组并通过串口发送出去
                    serialPort1.Write(buf.ToArray(), 0, buf.Count);
                    S_cnt  = buf.Count;//发送计数 
                }
                else//如果选择字符发送模式
                {
                    if (sendnewline.Checked == true)//选择发送新行时
                    {
                        string res = sendbuf.Text   "\r\n";
                        byte[] byteArray = System.Text.Encoding.Default.GetBytes(res);
                        serialPort1.Write(byteArray, 0, byteArray.Length);
                        S_cnt  = byteArray.Length;//发送计数 
                    }
                    else
                    {
                        byte[] byteArray = System.Text.Encoding.Default.GetBytes(sendbuf.Text);
                        serialPort1.Write(byteArray, 0, byteArray.Length);
                        S_cnt  = byteArray.Length;//发送计数 
                    }
                }
            }
            catch (Exception ex)
            {
                
            }
        }
        /// <summary>
        /// 发送区输入内容判断
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void txtSendDelay_KeyPress(object sender, KeyPressEventArgs e)
        {
            try
            {
                if (
                       (
                            ((e.KeyChar) >= '0') &&
                            ((e.KeyChar) <= '9')
                       )
                       || ((e.KeyChar) == '\b')
                   )
                {

                }
                else
                {
                    MessageBox.Show("请输出正确的格式 0-9");
                }
                e.Handled = "0123456789".IndexOf(char.ToUpper(e.KeyChar)) < 0;
            }
            catch (Exception ex)
            {
                
            }
        }
        /// <summary>
        /// 定时发送实现函数
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void timersend_CheckedChanged(object sender, EventArgs e)
        {
            int timer;
            try
            {
                Int32.TryParse(SendDelay.Text,out timer);
                if (timersend.Checked == true)
                {
                    if (timer == 0)////转换为int类型 
                    {
                        MessageBox.Show("请输入定时时间");
                        timersend.Checked = false;
                        return;
                    }
                    timer1.Enabled = true;
                    timer1.Interval = timer; //定时器时间间隔 
                    timer1.Start();   //定时器开始工作
                }
                else
                {
                    timer1.Enabled = false;
                    timer1.Stop();
                }
            }
            catch (Exception ex)
            {
                
            }
        }

        private void timer2_Tick(object sender, EventArgs e)
        {
            try
            {
                DateTime dt = DateTime.Now;
                datatime.Text = dt.ToString();//2005-11-5 13:21:25
                lblRCount.Text = R_cnt.ToString();
                lblSCount.Text = S_cnt.ToString();
            }
            catch (Exception ex)
            {
            
            }
        }
        /// <summary>
        /// 清空计数函数
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void clrcnt_Click(object sender, EventArgs e)
        {
            try
            {
                S_cnt = 0;//发送计数 
                R_cnt = 0;//接收计数 
                lblRCount.Text = "0";
                lblSCount.Text = "0";
                sendprogressBar.Value = 0;//设置进度条的初始值 
                sendprogressBar.Minimum = 0;//设置progressBar1控件的Minimum值为0 
                sendprogressBar.Maximum = 100;//设置progressBar1的Maximum值为500 
                sendpercentage.Text = "0%";
            }
            catch (Exception ex)
            {
              
            }
        }
        /// <summary>
        /// 打开文件函数
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void OpenFile_Click(object sender, EventArgs e)
        {
            try
            {
                //首先,实例化对话框类实例
                OpenFileDialog openDialog = new OpenFileDialog();
                //然后,判断如果当前用户在对话框里点击的是OK按钮的话。
                if (DialogResult.OK == openDialog.ShowDialog())
                {
                    //将打开文件对话框的FileName属性传递到你的字符串进行处理
                    filename = openDialog.FileName;
                }
            }
            catch (Exception ex)
            {
               
            }
        }
        /// <summary>
        /// 发送文件函数
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void SendFile_Click(object sender, EventArgs e)
        {
            try
            {
                if (filename == null)
                {
                    MessageBox.Show("请选择要发送的文件");
                    return;
                }
                SendFile.Enabled = false;//发送文件键失效
                send.Enabled = false;//"发送"按键失效
                timersend.Checked = false;
                timersend.Enabled = false;//失效
                if (Sending_Flag == false)//正在发送文件标志
                {
                    Sending_Flag = true;
                }
                Thread t = new Thread(new ThreadStart(sendfile));//创建了线程还未开启
                t.Start();//用来给函数传递参数,开启线程
                sendprogressBar.Value = 0;//设置进度条的初始值 
                sendprogressBar.Minimum = 0;//设置progressBar1控件的Minimum值为0 
                sendprogressBar.Maximum = 100;//设置progressBar1的Maximum值为500 
                sendpercentage.Text = "0%";
                index = 0;
            }
            catch (Exception ex)
            {
                SendFile.Enabled = true;//
                send.Enabled = true;//"发送"按键使能
                timersend.Enabled = true;//失效
                return;
            }
        }
        /// <summary>
        /// 停止发送函数
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void stopsend_Click(object sender, EventArgs e)
        {
            if (Sending_Flag == true)//正在发送文件标志
            {
                Sending_Flag = false;//正在发送文件标志
            }
        }
    }
}

实例下载地址

C#串口助手源码(向串口发送数据以及接收串口数据,支持发送文件)

不能下载?内容有错? 点击这里报错 + 投诉 + 提问

好例子网口号:伸出你的我的手 — 分享

网友评论

发表评论

(您的评论需要经过审核才能显示)

查看所有0条评论>>

小贴士

感谢您为本站写下的评论,您的评论对其它用户来说具有重要的参考价值,所以请认真填写。

  • 类似“顶”、“沙发”之类没有营养的文字,对勤劳贡献的楼主来说是令人沮丧的反馈信息。
  • 相信您也不想看到一排文字/表情墙,所以请不要反馈意义不大的重复字符,也请尽量不要纯表情的回复。
  • 提问之前请再仔细看一遍楼主的说明,或许是您遗漏了。
  • 请勿到处挖坑绊人、招贴广告。既占空间让人厌烦,又没人会搭理,于人于己都无利。

关于好例子网

本站旨在为广大IT学习爱好者提供一个非营利性互相学习交流分享平台。本站所有资源都可以被免费获取学习研究。本站资源来自网友分享,对搜索内容的合法性不具有预见性、识别性、控制性,仅供学习研究,请务必在下载后24小时内给予删除,不得用于其他任何用途,否则后果自负。基于互联网的特殊性,平台无法对用户传输的作品、信息、内容的权属或合法性、安全性、合规性、真实性、科学性、完整权、有效性等进行实质审查;无论平台是否已进行审查,用户均应自行承担因其传输的作品、信息、内容而可能或已经产生的侵权或权属纠纷等法律责任。本站所有资源不代表本站的观点或立场,基于网友分享,根据中国法律《信息网络传播权保护条例》第二十二与二十三条之规定,若资源存在侵权或相关问题请联系本站客服人员,点此联系我们。关于更多版权及免责申明参见 版权及免责申明

;
报警