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