基於C# Winform的串列埠資料接收
阿新 • • 發佈:2018-12-01
https://blog.csdn.net/woolnil/article/details/78048272
今天,我分享一篇文章,講述 基於C# Winform的串列埠資料接收程式設計(適合大概明白WinForm程式設計的同學,沒有接觸過WinForm的同學下載原始碼學習)
首先新增串列埠(自行拖拽)
[csharp] view plain copy
- SerialPort serialPort1 =
建立一個數據接收方法
[csharp] view plain copy
- void Comm_DataReceived(
- {
- Byte[] InputBuf = new Byte[128];
-
- try
- {
- serialPort1.Read(InputBuf, 0, serialPort1.BytesToRead); //讀取緩衝區的資料直到“}”即0x7D為結束符
- //InputBuf = UnicodeEncoding.Default.GetBytes(strRD); //將得到的資料轉換成byte的格式
- System.Threading.Thread.Sleep(50);
- this.Invoke(disp_delegate, InputBuf);
- }
- catch (TimeoutException ex) //超時處理
- {
- MessageBox.Show(ex.ToString());
- }
- }
建立一個委託事件:(關於C#委託事件,下文會有參考文章)
[csharp] view plain copy
- public void DispUI(byte[] InputBuf)
- {
- //textBox1.Text = Convert.ToString(InputBuf);
- ASCIIEncoding encoding = new ASCIIEncoding();
- richTextBox1.Text = encoding.GetString(InputBuf);
- }
完整的程式程式碼:
[csharp] view plain copy
- 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.Ports;
- namespace WindowsFormsApplication3
- {
- public partial class Form1 : Form
- {
- SerialPort serialPort1 = new SerialPort("COM2", 9600, Parity.None, 8, StopBits.One); //初始化串列埠設定
- public delegate void Displaydelegate(byte[] InputBuf);
- Byte[] OutputBuf = new Byte[128];
- public Displaydelegate disp_delegate;
- public Form1()
- {
- disp_delegate = new Displaydelegate(DispUI);
- serialPort1.DataReceived += new SerialDataReceivedEventHandler(Comm_DataReceived);
- InitializeComponent();
- }
- private void button1_Click(object sender, EventArgs e)
- {
- try
- {
- if (button1.Text == "開啟")
- {
- serialPort1.Open();
- button1.Text = "關閉";
- }
- else
- {
- serialPort1.Close();
- button1.Text = "開啟";
- }
- }
- catch (Exception ex)
- {
- MessageBox.Show(ex.Message, "錯誤提示", MessageBoxButtons.OK, MessageBoxIcon.Error);
- return;
- }
- }
- void Comm_DataReceived(object sender, SerialDataReceivedEventArgs e)
- {
- Byte[] InputBuf = new Byte[128];
- try
- {
- serialPort1.Read(InputBuf, 0, serialPort1.BytesToRead); //讀取緩衝區的資料直到“}”即0x7D為結束符
- //InputBuf = UnicodeEncoding.Default.GetBytes(strRD); //將得到的資料轉換成byte的格式
- System.Threading.Thread.Sleep(50);
- this.Invoke(disp_delegate, InputBuf);
- }
- catch (TimeoutException ex) //超時處理
- {
- MessageBox.Show(ex.ToString());
- }
- }
- public void DispUI(byte[] InputBuf)
- {
- //textBox1.Text = Convert.ToString(InputBuf);
- ASCIIEncoding encoding = new ASCIIEncoding();
- richTextBox1.Text = encoding.GetString(InputBuf);
- }
- }
- }