关于事件处理(C#)

来源:岁月联盟 编辑:zhu 时间:2003-07-12
为了在应用中使用事件,你必须提供一个用来响应事件执行程序逻辑的事件处理器(一个事件处理的方法),和向事件源登记事件处理器.这个过程,被称为事件线.下面分别在,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中看关于,事件和委托的教程.