.net教程:关于事件处理(c#)
为了在应用中使用事件,你必须提供一个用来响应事件执行程序逻辑的事件处理器(一个事件处理的方法),和向事件源登记事件处理器.这个过程,被称为事件线.下面分别在,web forms和windows forms说明,怎样工作的.
1.web forms:
例子中,有一个butto和一个textbox,当点击按钮时,文本框,改变背景颜色.
<html>
<script language="c#" runat=server>
private void button_clicked(object sender, eventargs e){
box.backcolor = system.drawing.color.lightgreen;
}
</script>
<body>
<form method="post" action="events.aspx" runat=server>
click the button, and notice the color of the text box.<br><br>
<asp:textbox
id = "box" text = "hello" backcolor = "cyan" runat=server/>
<br><br>
<asp:button
id = "button" onclick = "button_clicked" text = "click me"
runat = server/>
</form>
</body>
</html>
保存,生成events.aspx文件,通过,浏览器,可以看到效果.
下面简要的说明,在例子中,实质的几步.
1.事件源是一个"system.webforms.ui.webcontrols.button" server control的实例.
2.按钮产生一个click事件.
3.click事件的委托是eventhandler.
4.页面有一个事件处理器调用button_clicked.
5.click事件用下面的语法"onclick = "button_clicked"和button_clicked关连.
对于实际的web开发者来说,不必关心委托的细节,就像上面的例子一样,简单的实现了事件.
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中看关于