本文介绍了创建自定义事件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

可以自定义事件的任何对象方法创建结果
。要做到这一点就我只是用的语法如下:??



  myObject.myMethod + =新的EventHandler(myNameEvent); 



下面的代码,促使这个问题:

 私人无效btRunProcessAndRefresh_Click(对象发件人,EventArgs五)
{
myProcess =新工艺();
myProcess.StartInfo.FileName = @C:\ConsoleApplication4.exe
myProcess.Exited + =新的EventHandler(MyProcessExited);
myProcess.EnableRaisingEvents = TRUE;
myProcess.SynchronizingObject =这一点;
btRunProcessAndRefresh.Enabled = FALSE;
myProcess.Start();
}


解决方案

是的,你可以这样做







 公共类节拍器
{
公共事件TickHandler蜱;
公共EventArgs的= NULL;
公众委托无效TickHandler(节拍器男,EventArgs的);
公共无效启动()
{
,而(真)
{
System.Threading.Thread.Sleep(3000);
如果(蜱!= NULL)
{
蜱(这一点,E);
}
}
}
}
公共类监听器
{
公共无效订阅(节拍器米)
{
m.Tick + =新Metronome.TickHandler(HeardIt);
}
}
类测试
{
静态无效的主要()
{
节拍器M =新节拍器();
侦听器l =新监听器();
l.Subscribe(米);
m.Start();
}
}


Can a custom event be created for any object method?
To do this do I just use the following syntax?:

myObject.myMethod +=new EventHandler(myNameEvent);

The following code has prompted this question:

   private void btRunProcessAndRefresh_Click(object sender,EventArgs e)
    {
        myProcess =new Process();
        myProcess.StartInfo.FileName = @"c:\ConsoleApplication4.exe";
        myProcess.Exited += new EventHandler(MyProcessExited);
        myProcess.EnableRaisingEvents =true;
        myProcess.SynchronizingObject =this;
        btRunProcessAndRefresh.Enabled =false;
        myProcess.Start();
    }
解决方案

Yes you can do like this :

Creating advanced C# custom events

or

The Simplest C# Events Example Imaginable

 public class Metronome
    {
        public event TickHandler Tick;
        public EventArgs e = null;
        public delegate void TickHandler(Metronome m, EventArgs e);
        public void Start()
        {
            while (true)
            {
                System.Threading.Thread.Sleep(3000);
                if (Tick != null)
                {
                    Tick(this, e);
                }
            }
        }
    }
    public class Listener
    {
        public void Subscribe(Metronome m)
        {
            m.Tick += new Metronome.TickHandler(HeardIt);
        }
    }
    class Test
    {
        static void Main()
        {
            Metronome m = new Metronome();
            Listener l = new Listener();
            l.Subscribe(m);
            m.Start();
        }
    }

这篇关于创建自定义事件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-14 09:59