C# 委託,事件 實例

 

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace OnKeyDown
{
    class Program
    {
        static void Main(string[] args)
        {
            //實例化一個事件發送器
            KeyInputMonitor monitor = new KeyInputMonitor();

            //實例化一個事件接收器
            EventReceiver eventReceiver = new EventReceiver(monitor);

            //運行
            monitor.Run();
        }
    }

    internal class KeyEventArgs : EventArgs
    {
        private char keyChar;
        public KeyEventArgs(char keyChar) : base()
        {
            this.keyChar = keyChar;
        }

        public char KeyChar
        {
            get
            {
                return keyChar;
            }
        }
    }

    internal class KeyInputMonitor
    {
        //創建一個委託,返回類型爲void,兩個參數
        public delegate void KeyDown(object sender, KeyEventArgs e);

        //將創建的委託和特定事件關聯,在這裏特定的事件爲OnKeyDown
        public event KeyDown OnKeyDown;

        public void Run()
        {
            bool finished = false;
            do
            {
                Console.WriteLine("Input a char");
                string response = Console.ReadLine();

                char responseChar = (response == "") ? ' ' : char.ToUpper(response[0]);
                switch(responseChar)
                {
                    case 'X':
                        finished = true;
                        break;
                    default:
                        //得到按鍵信息的參數
                        KeyEventArgs keyEventArgs = new KeyEventArgs(responseChar);

                        //觸發事件
                        OnKeyDown(this, keyEventArgs);
                        break;
                }
            }while(!finished);
        }
    }

    internal class EventReceiver
    {
        public EventReceiver(KeyInputMonitor monitor)
        {
            //產生一個委託實例並添加到KeyInputMonitor產生的事件列表中
            monitor.OnKeyDown += new KeyInputMonitor.KeyDown(this.Echo);
        }

        private void Echo(object sender, KeyEventArgs e)
        {
            //真正的事件處理函數
            Console.WriteLine("Capture key: {0}", e.KeyChar);
        }
    }
}

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章