C# WindowsForms Raise, consume Events

本文关键字:consume Events Raise WindowsForms | 更新日期: 2023-09-27 18:33:16

我在下面有这段代码:

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

C# WindowsForms Raise, consume Events

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!";
}