以下是模擬我們點擊鼠標,然后執(zhí)行事件函數(shù)的整個過程。 using System;
using System.Collections.Generic; using System.Linq; using System.Text; namespace 模擬按鈕事件觸發(fā)過程
{ /// <summary> /// 事件委托 /// </summary> /// <param name="sender"></param> /// <param name="e"></param> public delegate void EventHandle(object sender, EventArgs e); class Program { static void Main(string[] args) { Button btn = new Button(); btn.Click += new EventHandle(btn_Click); Trigger(btn,EventArgs.Empty);//相當于鼠標點擊觸發(fā) Console.Read(); } static void btn_Click(object sender, EventArgs e)
{ Button btn = (Button)sender; btn.Text = "模擬按鈕點擊事件"; Console.WriteLine(btn.Text); } /// <summary> /// /// 用戶單擊了窗體中的按鈕后,Windows就會給按鈕消息處理程序(WndPro)發(fā)送一個WM_MOUSECLICK消息 /// /// </summary> /// <param name="btn"></param> /// /// <param name="e"></param> static void Trigger(Button btn, EventArgs e) { btn.OnClick(e); } } /// <summary> /// 模擬Button /// </summary> public class Button { private string txt; public string Text { get { return txt; } set { txt = value; } } public event EventHandle Click;//定義按鈕點擊事件 /// <summary> /// /// 事件執(zhí)行方法 /// /// </summary> /// <param name="sender"></param> /// /// <param name="e"></param> void ActionEvent(object sender, EventArgs e) { if (Click == null) Click += new EventHandle(Err_ActionEvent); Click(sender, e);//這一部執(zhí)行了Program中的btn_Click方法 } void Err_ActionEvent(object sender, EventArgs e) { throw new Exception("The method or operation is not implemented."); } public void OnClick(EventArgs e) { ActionEvent(this, e); } } } 用戶單擊了窗體中的按鈕后,Windows就會給按鈕消息處理程序(WndPro)發(fā)送一個WM_MOUSECLICK消息,對于.NET開發(fā)人員來說,就是按鈕的OnClick事件。
從客戶的角度討論事件: 事件接收器是指在發(fā)生某些事情時被通知的任何應用程序、對象或組件(在上面的Demo中可以理解為Button類的實例btn)。有事件接收器就有事件發(fā)送器。發(fā)送器的作用就是引發(fā)事件。發(fā)送器可以是應用程序中的另一個對象或者程序集(在上面的Demo中可以理解為程序集中的program引發(fā)事件),實際在系統(tǒng)事件中,例如鼠標單擊或鍵盤按鍵,發(fā)送器就是.NET運行庫。注意,事件的發(fā)送器并不知道接收器是誰。這就使得事件非常有用。 現(xiàn)在,在事件接收器的某個地方有一個方法(在Demo中位OnClick),它負責處理事件。在每次發(fā)生已注冊的事件時執(zhí)行事件處理程序(btn_Click)。此時就要用到委托了。由于發(fā)送器對接收器一無所知,所以無法設(shè)置兩者之間的引用類型,而是使用委托作為中介,發(fā)送器定義接收器要使用的委托,接受器將事件處理程序注冊到事件中,接受事件處理程序的過程成為封裝事件。 |
|