C# SerialPortHelper類

來源:互聯網
上載者:User

標籤:toolstrip   catch   handle   form   ++   void   substring   sub   new   

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<string>(                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))                {                }            }        }    }}


C# SerialPortHelper類

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.