以下是模擬我們點(diǎn)擊鼠標,然后執行事件函數的整個(gè)過(guò)程。
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace 模擬按鈕事件觸發(fā)過(guò)程
{
/// <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);//相當于鼠標點(diǎn)擊觸發(fā)
Console.Read();
}
static void btn_Click(object sender, EventArgs e)
{
Button btn = (Button)sender;
btn.Text = "模擬按鈕點(diǎn)擊事件";
Console.WriteLine(btn.Text);
}
/// <summary>
///
/// 用戶(hù)單擊了窗體中的按鈕后,Windows就會(huì )給按鈕消息處理程序(WndPro)發(fā)送一個(gè)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;//定義按鈕點(diǎn)擊事件
/// <summary>
/// /// 事件執行方法
/// /// </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);//這一部執行了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);
}
}
}
用戶(hù)單擊了窗體中的按鈕后,Windows就會(huì )給按鈕消息處理程序(WndPro)發(fā)送一個(gè)WM_MOUSECLICK消息,對于.NET開(kāi)發(fā)人員來(lái)說(shuō),就是按鈕的OnClick事件。
從客戶(hù)的角度討論事件:
事件接收器是指在發(fā)生某些事情時(shí)被通知的任何應用程序、對象或組件(在上面的Demo中可以理解為Button類(lèi)的實(shí)例btn)。有事件接收器就有事件發(fā)送器。發(fā)送器的作用就是引發(fā)事件。發(fā)送器可以是應用程序中的另一個(gè)對象或者程序集(在上面的Demo中可以理解為程序集中的program引發(fā)事件),實(shí)際在系統事件中,例如鼠標單擊或鍵盤(pán)按鍵,發(fā)送器就是.NET運行庫。注意,事件的發(fā)送器并不知道接收器是誰(shuí)。這就使得事件非常有用。
現在,在事件接收器的某個(gè)地方有一個(gè)方法(在Demo中位OnClick),它負責處理事件。在每次發(fā)生已注冊的事件時(shí)執行事件處理程序(btn_Click)。此時(shí)就要用到委托了。由于發(fā)送器對接收器一無(wú)所知,所以無(wú)法設置兩者之間的引用類(lèi)型,而是使用委托作為中介,發(fā)送器定義接收器要使用的委托,接受器將事件處理程序注冊到事件中,接受事件處理程序的過(guò)程成為封裝事件。
本站僅提供存儲服務(wù),所有內容均由用戶(hù)發(fā)布,如發(fā)現有害或侵權內容,請
點(diǎn)擊舉報。