本實例演示定義委托,並利用委托把來自串口接收到的數據顯示在文本框中!熟悉委托的定義和串行數據收發的簡單功能!
項目代碼:
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 { ////// QQ 458978 無名 C#開發技術 歡迎和我交流探討 /// public partial class Form1 : Form { ////// 定義委托 /// ///public delegate void ShowString(string a); ////// 字符顯示在文本框 /// ///public void ShowTxt(string a) { this.textBox1.AppendText(DateTime.Now.ToString() + | + a + ); if (textBox1.TextLength > 2000) { textBox1.Clear(); } } ////// 定義委托並初始化 /// ShowString AA; ////// 接收字符串存儲 /// 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); } } }
運行效果圖片: