我的代码如下:
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
答案 0 :(得分:0)
在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!";
}