[英]C# WindowsForms Raise, consume Events
I have this code below: 我在下面的代码:
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
}
}
}
}
I ve tried a lot to create some events, I even use this example : http://www.codeproject.com/Articles/11541/The-Simplest-C-Events-Example-Imaginable 我已经做了很多尝试来创建一些事件,甚至使用了以下示例: http : //www.codeproject.com/Articles/11541/The-Simplest-C-Events-Example-Imaginable
but I cant understant how to create an event with my classes... 但是我不能理解如何用我的班级创建一个事件...
I such a fool I know but I really need your help ! 我知道我真傻,但是我真的需要你的帮助!
Thanks the team !! 谢谢团队!
Regards. 问候。
FB FB
Define the event in the Process
class: 在
Process
类中定义事件:
public event EventHandler Finished;
Then in the same class define a method that raises the event "safely": 然后在同一类中定义一个“安全”引发事件的方法:
protected void RaiseFinished()
{
// Make sure the event has at least one subscriber.
if(Finished != null)
{
Finished(this, EventArgs.Empty);
}
}
You call the method where you want your event to be raised, in your case the start
method: 您可以在要引发事件的位置调用方法,在这种情况下,请使用
start
方法:
public void Start()
{
try
{
//Do something
//...
RaiseFinished();
}
catch (Exception e)
{
//do something with the exception
}
}
Then in your Main_GUI
class constructor subscribe to the event defining an handler: 然后在您的
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.