This example demonstrates defining a delegate and using a delegate to display the data received from the serial port in a text box! Familiar with the definition of delegates and the simple function of serial data sending and receiving!
This article source code, you can modify the code to run debugging, the serial port I use the COM11, you need to change to their own only good advice is COM1
http://download.csdn.net/detail/nieweiking/8245463
Project Code:
<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 unknown C # Development Technology Welcome to discuss with me///</summary> public par Tial class Form1:form {//<summary>/////</summary>//<param N Ame= "A" ></param> public delegate void Showstring (string a); <summary>////characters appear in text boxes///</summary>//<param name= "a" ></param> public void Showtxt (string a) {This.textBox1.AppendText (DateTime.Now.ToString () + "|" + A + "\ n"); if (Textbox1.textlength >) {textbox1.clear (); }}///<summary>//define delegates and initialize///</summary> showstring AA; <summary>///Receive string storage///</summary> string readstr = ""; Public Form1 () {InitializeComponent (); Serialport1.open (); AA = new showstring (showtxt);//Initialize Delegate}//serial port receives data and sends back the private void Serialport1_datareceived (object Sende R, 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); } }}
Running slices:
Use of C # delegates and serial communication receive events are displayed in the specified control