标签:blog http io ar os 使用 sp for on
本实例演示定义委托,并利用委托把来自串口接收到的数据显示在文本框中!熟悉委托的定义和串行数据收发的简单功能!
本文源代码下载地址,可以酌情修改代码运行调试,串口端口我使用的COM11,你需要改成自己的才好用建议是COM1
http://download.csdn.net/detail/nieweiking/8245463
项目代码:
<pre name="code" class="csharp">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 WindowsFormsApplication1 { /// <summary> /// QQ 458978 无名 C#开发技术 欢迎和我交流探讨 /// </summary> public partial class Form1 : Form { /// <summary> /// 定义委托 /// </summary> /// <param name="a"></param> public delegate void ShowString(string a); /// <summary> /// 字符显示在文本框 /// </summary> /// <param name="a"></param> public void ShowTxt(string a) { this.textBox1.AppendText(DateTime.Now.ToString() + " | " + a + "\n"); if (textBox1.TextLength > 2000) { textBox1.Clear(); } } /// <summary> /// 定义委托并初始化 /// </summary> ShowString AA; /// <summary> /// 接收字符串存储 /// </summary> string ReadStr = ""; public Form1() { InitializeComponent(); serialPort1.Open(); AA = new ShowString(ShowTxt);//初始化委托 } //串口收到数据并回发 private void serialPort1_DataReceived(object sender, System.IO.Ports.SerialDataReceivedEventArgs e) { ReadStr = serialPort1.ReadExisting(); byte[] ReadBuffer; ReadBuffer= System.Text.ASCIIEncoding.ASCII.GetBytes(ReadStr); this.Invoke(AA, ReadStr); serialPort1.Write(ReadBuffer, 0, ReadBuffer.Length); } } }
运行效果图片:
标签:blog http io ar os 使用 sp for on
原文地址:http://blog.csdn.net/nieweiking/article/details/41851565