標籤: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); } }}
運行片:
C#委託的使用和串列通訊接收事件顯示在指定控制項