C#事件解析
来源:互联网 发布:c语言printf和scanf 编辑:程序博客网 时间:2024/06/05 17:20
using System;using System.Collections.Generic;using System.ComponentModel;using System.Data;using System.Drawing;using System.Linq;using System.Text;using System.Windows.Forms;namespace MyEvent{ public partial class Form1 : Form { //创建一个委托 public delegate void ActionEventHandler(object sender, ActionCancelEventArgs ev); public static event ActionEventHandler Action;//定义事件 public Form1() { InitializeComponent(); //把两个button点击事件用同一个方法处理 button1.Click += new EventHandler(Button_Click); button2.Click += new EventHandler(Button_Click); } void Button_Click(object sender, EventArgs e) { Button bt = (Button)sender; label1.Text = "你现在点击的按钮是:"+bt.Text.ToString(); } public class ActionCancelEventArgs : System.ComponentModel.CancelEventArgs { string message = String.Empty; public ActionCancelEventArgs() : base() { } public ActionCancelEventArgs(bool cancel) : base(cancel) { } public ActionCancelEventArgs(bool cancel, string message) : base(cancel) { this.message = message; } public string Message { get { return message; } set { message = value; } } } protected void OnAction(object sender, ActionCancelEventArgs ev) { if (Action != null) { Action(sender, ev);//这里注意这一句,这就是触发事件的语句,并将事件交由Action委托来处理 //(就是在BusEntity中的Form1_Action方法) } } private void buttonRaise_Click(object sender, EventArgs e) { ActionCancelEventArgs cancelEvent = new ActionCancelEventArgs(); BusEntity busentity=new BusEntity(); OnAction(this, cancelEvent); if (cancelEvent.Cancel) { labelinfo.Text = cancelEvent.Message; } else { labelinfo.Text = busentity.TimeString; } } }}
using System;using System.Collections.Generic;using System.Linq;using System.Text;namespace MyEvent{ public class BusEntity { public string time = String.Empty; public BusEntity() { //产生一个委托实例并添加到Form1产生的事件列表中 Form1.Action += new Form1.ActionEventHandler(Form1_Action); } //事件处理程序 void Form1_Action(object sender, Form1.ActionCancelEventArgs ev) { ev.Cancel = !DoAction(); if (ev.Cancel) { ev.Message = "现在的时间秒数大于30。"; } } private bool DoAction() { bool retVal = false; DateTime tm = DateTime.Now; if (tm.Second < 30) { time = "现在的时间是:" + DateTime.Now.ToLongTimeString(); retVal = true; } else { time = ""; } return retVal; } public string TimeString { get { return time; } } }}
C#中使用事件需要的步骤:
1.创建一个委托
3.编写事件处理程序
4.利用编写的事件处理程序生成一个委托实例
5.把这个委托实例添加到产生事件对象的事件列表中去,这个过程又叫订阅事件
- C#事件-事件解析
- C#事件(event)解析
- C#事件(event)解析
- C#事件(event)解析
- C#事件解析
- C#事件(event)解析
- C#事件(event)解析
- C#事件(event)解析
- C#事件(event)解析
- C#事件(event)解析
- C#事件(event)解析
- C#事件(event)解析
- C#事件解析
- C#事件解析
- C#事件(event)解析
- C#事件(event)解析
- C#事件解析
- C#事件(event)解析
- Lost connection to MySQL server during query
- 从MSDN总结过来的PropertyGrid中ExpandableObjectConverter的应用
- 反向链接
- JQuery 利用Ajax判断链接 是否有效
- CentOs、RedHat、Ubuntu下安装jdk6
- C#事件解析
- Android--学习记录--TabHost(非继承TabActivity)
- 快逸报表和weblogic小结
- static响应单击事件
- windows程序设计(5)使用滚动条
- JavaScript 使用面向对象的技术创建高级 Web 应用程序
- 视频文件解码与起始码(startcode) 研究
- 去掉string中的空格
- select 手动输入