繁体   English   中英

C#WindowsForms引发,使用事件

[英]C# WindowsForms Raise, consume Events

我在下面的代码:

using System;
using System.Windows.Forms;

namespace MyCode
{
public partial class Main_GUI : Form
{

    //Attributes
    private Processes process;        
    //Constructor
    public Main_GUI()
    {
        InitializeComponent(); //a form with a button named BUTTON_Start, and a label named LABEL_log
        p =  new Processes();            
    }
    //OnClickStart
    private void BUTTON_Start_Click(object sender, EventArgs e)
    {
        try
        {
            LABEL_log.Text = "Started...";
            p.start();
        }
        catch (Exception ex)
        {
        //do something with the exception
        }
    }
}//End of Class

public class Processes 
{   
    //Constructor
    public Processes() { }

    //Methods
    public void start()
    {
        try
        {
            //Do something
            //...
            //when finished send an event the Main_GUI Class (Form) in order to change the LABEL_log.Text value to "finished !"             
        }
        catch (Exception e)
        {
            //do something with the exception
        }
    }
}   
}

我已经做了很多尝试来创建一些事件,甚至使用了以下示例: http : //www.codeproject.com/Articles/11541/The-Simplest-C-Events-Example-Imaginable

但是我不能理解如何用我的班级创建一个事件...

我知道我真傻,但是我真的需要你的帮助!

谢谢团队!

问候。

FB

Process类中定义事件:

public event EventHandler Finished;

然后在同一类中定义一个“安全”引发事件的方法:

protected void RaiseFinished()
{
    // Make sure the event has at least one subscriber.
    if(Finished != null)
    {
        Finished(this, EventArgs.Empty);
    }
}

您可以在要引发事件的位置调用方法,在这种情况下,请使用start方法:

public void Start()
{
    try
    {
        //Do something
        //...

        RaiseFinished();            
    }
    catch (Exception e)
    {
        //do something with the exception
    }
}

然后在您的Main_GUI类构造函数中订阅该事件,以定义处理程序:

//Constructor
public Main_GUI()
{
    InitializeComponent(); //a form with a button named BUTTON_Start, and a label named LABEL_log
    p =  new Processes();

    // Subscribe to the event.
    p.Finished += p_Finished;         
}

// This will get called when the Finished event is raised.
private void p_Finished(object sender, EventArgs e)
{
   LABEL_log.Text = "Finished!";
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM