詳解C#串口監聽的實現
C#串口監聽的實現在 Visual Stdio 2005中,對于串口操作Framework提供了一個很好的類接口-SerialPort,在這當中,串口數據的讀取與寫入有較大的不同。C#串口監聽的實現由于串口不知道數據何時到達,因此有兩種方法可以實現C#串口監聽之串口數據的讀取。1.用線程實時讀串口2.用事件觸發方式實現。但由于線程實時讀串口的效率不是十分高效,因此比較好的方法是事件觸發的方式。在SerialPort類中有DataReceived事件,當串口的讀緩存有數據到達時則觸發DataReceived事件,其中SerialPort.ReceivedBytesThreshold屬性決定了當串口讀緩存中數據多少個時才觸發DataReceived事件,默認為1。
此外,SerialPort.DataReceived事件運行比較特殊,其運行在輔線程,不能與主線程中的顯示數據控件直接進行數據傳輸,必須用間接的方式實現。
C#串口監聽實現一、創建WIndow項目,設計界面
C#串口監聽實現二、編寫實現代碼
- using System;
- using System.Collections.Generic;
- using System.ComponentModel;
- using System.Data;
- using System.Drawing;
- using System.Text;
- using System.Windows.Forms;
- using System.IO.Ports;
- //using Microsoft.VisualBasic.Devices;
- //C#串口監聽
- namespace Demo
- ...{
- public partial class Form1 : Form
- ...{
- public Form1()
- ...{
- InitializeComponent();
- }
- private SerialPort Sp = new SerialPort();
- public delegate void HandleInterfaceUpdataDelegate(string text);
- private HandleInterfaceUpdataDelegate interfaceUpdataHandle;
- private void Form1_Load(object sender, EventArgs e)
- ...{
- tbID.Focus();
- BtPause.Enabled = false;
- }
- private void UpdateTextBox(string text)
- ...{
- tbData.Text = text;
- }
- public void Sp_DataReceived(object sender,
- System.IO.Ports.SerialDataReceivedEventArgs e)
- ...{
- byte[] readBuffer = new byte[Sp.ReadBufferSize];
- Sp.Read(readBuffer, 0, readBuffer.Length);
- this.Invoke(interfaceUpdataHandle,
- new string[] ...{ Encoding.UTF8.GetString(readBuffer) });
- }
- private void Form1_FormClosing(
- object sender, FormClosingEventArgs e)
- ...{
- Sp.Close();
- }
- private void btENT_Click(object sender, EventArgs e)
- ...{
- if ((tbID.Text.Trim() != "") &&
- (cmRate.Text != ""))
- ...{
- interfaceUpdataHandle =
- new HandleInterfaceUpdataDelegate(UpdateTextBox);
- //C#串口監聽之實例化委托對象
- Sp.PortName = tbID.Text.Trim();
- serialPort1.BaudRate =
- Convert.ToInt32(cmRate.Text.Trim());
- Sp.Parity = Parity.None;
- Sp.StopBits = StopBits.One;
- Sp.DataReceived +=
- new SerialDataReceivedEventHandler(Sp_DataReceived);
- Sp.ReceivedBytesThreshold = 1;
- try
- ...{
- Sp.Open();
- tbID.ReadOnly = true;
- BtPause.Enabled = true;
- btENT.Enabled = false;
- }
- catch
- ...{
- MessageBox.Show(
- "端口" + tbID.Text.Trim() + "打開失敗!");
- }
- }//C#串口監聽
- else
- ...{
- MessageBox.Show("請輸入正確的端口號和波特率!");
- tbID.Focus();
- }
- }
- private void BtPause_Click(
- object sender, EventArgs e)
- ...{
- Sp.Close();
- tbID.ReadOnly = false;
- btENT.Enabled = true;
- BtPause.Enabled = false;
- }
- }//C#串口監聽
- }
C#串口監聽具體的實現操作就向你介紹到這里,希望對你了解和學習C#串口監聽的實現有所幫助。
【編輯推薦】