using System;
using System.IO.Ports;
using System.Text;
using System.Threading;
using System.Windows.Forms;
namespace Serial
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
//初始化串口信息
SerialPort sp =new SerialPort("COM3", 9600, Parity.None, 8, StopBits.One);
private void Form1_Load(object sender, EventArgs e)
{
sp.DataReceived += Sp_DataReceived; //注册接收事件
sp.ReceivedBytesThreshold = 1; //接收到一个字节就触发事件
sp.Encoding = Encoding.Default; //设置编码,避免中文乱码
sp.Open(); //打开串口
}
//接收方法
private void Sp_DataReceived(object sender, SerialDataReceivedEventArgs e)
{
//数据接收完整性
//这里不知道是用延时好,还是循环读取缓冲区好,待验证……
//Thread.Sleep(50);
string data = string.Empty;
while (sp.BytesToRead > 0)
{
data += sp.ReadExisting(); //数据读取,直到读完缓冲区数据
}
//更新界面内容时UI不会卡
this.Invoke((EventHandler) delegate
{
//定义一个textBox控件用于接收消息并显示
textBox1.AppendText(data + Environment.NewLine);
});
}
}
}