博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
C# SerialPortHelper类
阅读量:5080 次
发布时间:2019-06-12

本文共 7577 字,大约阅读时间需要 25 分钟。

using System;using System.IO.Ports;class SerialPortHelper{    private long _receiveByteCount = 0, _sendByteOfCount = 0;    public long ReceiveByteCount { get { return _receiveByteCount; } set { _receiveByteCount = value; } }    public long SendByteOfCount { get { return _sendByteOfCount; } set { _sendByteOfCount = value; } }    SerialPort _serialPort = new SerialPort();    private DataReceived _received = null;    public delegate void DataReceived(byte[] data);    public bool IsOpen { get { return _serialPort.IsOpen; } }    public static string[] SerialPortNames    {        get        {            string[] serialports = SerialPort.GetPortNames();            Array.Sort(serialports, new Comparison
( delegate(string x, string y) { if (x.Length > 3 && y.Length > 3) { string index1 = x.Substring(3); string index2 = y.Substring(3); try { int n1 = Convert.ToInt32(index1); int n2 = Convert.ToInt32(index2); return n1 - n2; } catch { } } return 0; })); return serialports; } } public SerialPortHelper(DataReceived received) { _received = received; _serialPort.NewLine = "\r\n"; _serialPort.DataReceived += delegate { System.Threading.Thread.Sleep(50); int ReadLength = _serialPort.BytesToRead; if (ReadLength > 0) { _receiveByteCount += ReadLength; byte[] ReadBuffer = new byte[ReadLength]; _serialPort.Read(ReadBuffer, 0, ReadLength); if(_received!=null) { _received(ReadBuffer); } } }; } public void Open(string PortName) { _serialPort.PortName = PortName; _serialPort.StopBits = StopBits.One; _serialPort.Parity = Parity.None; _serialPort.DataBits = 8; _serialPort.BaudRate = 19200; _serialPort.Open(); } public void Close() { _serialPort.Close(); } public void WriteLine(string text) { if (_serialPort.IsOpen) { _sendByteOfCount += text.Length; _serialPort.WriteLine(text); } } public void Write(byte[] buffer) { if (_serialPort.IsOpen) { _serialPort.Write(buffer, 0, buffer.Length); _sendByteOfCount += buffer.Length; } }}

调用:

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;namespace SerialnumPort1{    public partial class Form1 : Form    {        string _tempfile = AppDomain.CurrentDomain.BaseDirectory + "temp.data";        SerialPortHelper _helper = null;        public Form1()        {            InitializeComponent();            _helper = new SerialPortHelper(delegate(byte[] data)                                                                    {                                                                        this.Invoke(                                                                         (EventHandler)delegate                                                                         {                                                                             if (checkBox2.Checked)                                                                             {                                                                                 using (System.IO.FileStream fs = new System.IO.FileStream(_tempfile, System.IO.FileMode.Append))                                                                                 {                                                                                     fs.Write(data, 0, data.Length);                                                                                 }                                                                             }                                                                             StringBuilder readStr = new StringBuilder();                                                                             foreach (byte b in data)                                                                             {                                                                                 string temp = string.Format("{0:X2} ", b);                                                                                 readStr.Append(temp);                                                                             }                                                                             readStr.Append("已接收\r\n");                                                                             toolStripStatusLabel1.Text = "已接收字节数:" + _helper.ReceiveByteCount;                                                                             richTextBox1.AppendText(readStr.ToString());                                                                             richTextBox1.ScrollToCaret();                                                                         }                                                                        );                                                                    });        }        private void Form1_Load(object sender, EventArgs e)        {            string[] serialnums = SerialPortHelper.SerialPortNames;            comboBox1.Items.AddRange(serialnums);        }        private void button2_Click(object sender, EventArgs e)        {            if ("打开" == button2.Text)            {                try                {                    _helper.Open(comboBox1.Text);                    button2.Text = "关闭";                }                catch (Exception ex)                {                    MessageBox.Show(ex.Message + "\r\n" + ex.StackTrace);                }            }            else            {                button2.Text = "打开";                _helper.Close();            }        }        private void button1_Click(object sender, EventArgs e)        {            if (_helper.IsOpen)            {                if (!checkBox1.Checked)                {                    _helper.WriteLine(textBox1.Text);                }                else                {                    string sendtext = textBox1.Text.TrimEnd(' ');                    string[] sps = sendtext.Split(' ');                    byte[] sendata = new byte[sps.Length];                    for (int i = 0; i < sendata.Length; ++i)                    {                        sendata[i] = (byte)Convert.ToInt32(sps[i], 16);                    }                    _helper.Write(sendata);                }                richTextBox1.AppendText(textBox1.Text + " 已发送\r\n");                richTextBox1.ScrollToCaret();                toolStripStatusLabel2.Text = "已发送字节数:" + _helper.SendByteOfCount;            }        }        private void checkBox2_CheckedChanged(object sender, EventArgs e)        {            if (checkBox2.Checked)            {                System.IO.File.Delete(_tempfile);                using (System.IO.FileStream fs = System.IO.File.Create(_tempfile))                {                }            }        }    }}

转载于:https://www.cnblogs.com/wzzkaifa/p/6727094.html

你可能感兴趣的文章
页面中公用的全选按钮,单选按钮组件的编写
查看>>
java笔记--用ThreadLocal管理线程,Callable<V>接口实现有返回值的线程
查看>>
BZOJ 1047 HAOI2007 理想的正方形 单调队列
查看>>
各种语言推断是否是手机设备
查看>>
这个看起来有点简单!--------实验吧
查看>>
PHP count down
查看>>
JVM参数调优:Eclipse启动实践
查看>>
(旧笔记搬家)struts.xml中单独页面跳转的配置
查看>>
不定期周末福利:数据结构与算法学习书单
查看>>
strlen函数
查看>>
python的列表与shell的数组
查看>>
关于TFS2010使用常见问题
查看>>
软件工程团队作业3
查看>>
python标准库——queue模块 的queue类(单向队列)
查看>>
火狐、谷歌、IE关于document.body.scrollTop和document.documentElement.scrollTop 以及值为0的问题...
查看>>
深入理解JVM读书笔记--字节码执行引擎
查看>>
vue-搜索功能-实时监听搜索框的输入,N毫秒请求一次数据
查看>>
批处理 windows 服务的安装与卸载
查看>>
React文档翻译 (快速入门)
查看>>
nodejs fs路径
查看>>