者來說,不必關心委托的細節,就像上面的例子一樣,簡單的實現了事件.
2.windows forms
例子中,有一個butto和一個textbox,當點擊按鈕時,文本框,改變背景顏色.
using system;
using system.componentmodel;
using system.windows.forms;
using system.drawing;
public class myform : form
{
private textbox box;
private button button;
public myform() : base()
{
box = new textbox();
box.backcolor = system.drawing.color.cyan;
box.size = new size(100,100);
box.location = new point(50,50);
box.text = "hello";
button = new button();
button.location = new point(50,100);
button.text = "click me";
//為了關連事件,生成一個委托實例同時增加它給click事件.
button.click += new eventhandler(this.button_clicked);
controls.add(box);
controls.add(button);
}
//事件處理器
private void button_clicked(object sender, eventargs e)
{
box.backcolor = system.drawing.color.green;
}
// stathreadattribute說明windows forms使用單線程套間模型.
[stathreadattribute]
public static void main(string[] args)
{
application.run(new myform());
}
}
保存"events.cs",在命令行中輸入,以下
csc /r:system.dll,system.drawing.dll,system.windows.forms.dll events.cs
編譯生成,events.exe,執行,可看到效果.
上面的例子,簡單的說明了.net中,事件的處理.一個事件,必須有事件源,和事件數據.在例子中,事件數據用evengargs.它是所有事件數據類的基類.
為了更好的理解事件.可以去msdn中看關于,事件和委托的教程.