C#委托的使用和串行通讯接收事件显示在指定控件

本实例演示定义委托,并利用委托把来自串口接收到的数据显示在文本框中!熟悉委托的定义和串行数据收发的简单功能!


本文源代码下载地址,可以酌情修改代码运行调试,串口端口我使用的COM11,你需要改成自己的才好用建议是COM1

http://download.csdn.net/detail/nieweiking/8245463

项目代码:

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 + "\n");
            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);
        }
    }
}


 
  

运行效果图片:


C#委托的使用和串行通讯接收事件显示在指定控件_第1张图片



你可能感兴趣的:(C#开发技术)