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.把这个委托实例添加到产生事件对象的事件列表中去,这个过程又叫订阅事件