C#委託的使用和串列通訊接收事件顯示在指定控制項

來源:互聯網
上載者:User

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

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.