C# 事件的简单例子

事件的简单例子
using System.Windows,Form;
public class Form1:Form
{
    public delegate void ActionEventHandler(object sender,ActionCancelEventArgs ev);//定义委托类型ActionEventHandler
    public static event ActionEventHandler Action;//定义事件
    
    BusEntity busEntity=new BusEntity();
    
    public Form()
    {
        InitializeComponent();
    }
    
    /*public void Form1_Load()
    {
        ActionCancelEventArgs e = new ActionCancelEventArgs();
        Action+=new ActionEventHandler(OnAction);//触发事件
    }*/
    
    public static void OnAction(object sender,ActionCancelEventArgs ev)
    {
        if(Action!=null)
        {
            Action(sender,ev);
        }
    }
    
    private void btnRaise_Click(object sender,EventAgrs e)
    {
        ActionCancelEventArgs cancelEvent=new ActionCancelEventArgs();
        OnAction(this,cancelEvent);
        if(cancelEvent.Cancel)
        {
            lblInfo.Text=cancelEvent.Message;
        }
        else
        {
            lblInfo.Text=busEntity.TimeString;
        }
    }
}

public class ActionCancelEventArgs:System.ComponentModel.CancelEventArgs
{
    public string Message
    {get;set;}
    public ActionCancelEventArgs():this(false){}//构造函数
    
    public ActionCancelEventArgs(bool cancel):this(false,""){}//构造函数
    
    public ActionCancelEventArgs(bool cancel,string message):base(cancel)//构造函数
    {
        this.message=message;
    }
}
/*
基于EventArgs的新类ActionCancelEventArgs派生自CancelEventArgs,CancelEventArgs
派生自EventArgs。CancelEventArgs添加了Cancel属性,该属性是一布尔值,它通知Senser
对象,接收器希望取消或停止事件的处理。在ActionCancelEventArgs里还添加了
Message属性。
*/

using System;
namespace test
{
    public class BusEntity
    {
        string time="";
        
        public BusEntity()
        {
            Form1.Action += new Form1.ActionEventHandler(Form1_Action); 
        }
        
        private void Form1_Action(object sender,ActionCancelEventArgs e)
        {
            e.Cancel=! DoActions();
            if(e.Cancel)
            {
                e.Message="wasn't the right time";
            }
        }
        
        private bool DoActions()
        {
            bool retVal=false;
            DateTime tm=DateTime.Now;
            
            if(tm.Second<30)
            {
                time="the tine is"+DateTime.Now.ToLongTimeString();
                retVal=true;
            }
            else
            {
                time="":
                return retVal;
            }
        }
        
        public string TimeString
        {
            get
            {
                return time;
            }
        }
    }
}

 

posted on 2012-09-14 10:18  refactor  阅读(2097)  评论(0编辑  收藏  举报

导航