C#实现串口监听

Visual Stdio 2005中,对于串口操作Framework提供了一个很好的类接口-SerialPort,在这当中,串口数据的读取与写入有较大的不同。由于串口不知道数据何时到达,因此有两种方法可以实现串口数据的读取。

       1.用线程实时读串口

       2.用事件触发方式实现。

        但由于线程实时读串口的效率不是十分高效,因此比较好的方法是事件触发的方式。在SerialPort类中有DataReceived事件,当串口的读缓存有数据到达时则触发DataReceived事件,其中SerialPort.ReceivedBytesThreshold属性决定了当串口读缓存中数据多少个时才触发DataReceived事件,默认为1。

       此外,SerialPort.DataReceived事件运行比较特殊,其运行在辅线程,不能与主线程中的显示数据控件直接进行数据传输,必须用间接的方式实现。

一.创建WIndow项目,设计界面

二,编写实现代码

 

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;


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);//实例化委托对象
                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() + "打开失败!");
                }

            }

            
else
            
...{
                MessageBox.Show(
"请输入正确的端口号和波特率!");
                tbID.Focus();
            }

        }


        
private void BtPause_Click(object sender, EventArgs e)
        
...{
            Sp.Close();
            tbID.ReadOnly 
= false;
            btENT.Enabled 
= true;
            BtPause.Enabled 
= false;
        }

    }

}

 

占华

http://www.cardprinterworld.com

  • 4
    点赞
  • 28
    收藏
    觉得还不错? 一键收藏
  • 5
    评论
评论 5
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值