者来说,不必关心委托的细节,就像上面的例子一样,简单的实现了事件.
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中看关于,事件和委托的教程.