说明:
SelfeEntrust、ShowEvent是可以自己定义的委托和事件。
在需要被调用的类中定义委托和事件
namespace ElectronicNose
{
public partial class Form1 : Form
{
public delegate void SelfeEntrust(); //定义委托
public event SelfeEntrust ShowEvent; //定义事件
}
private void btn_Confirm_Click(object sender, EventArgs e)
{
ShowEvent();
}
}
将方法绑定到委托
namespace ElectronicNose
{
public partial class Form2 : Form
{
}
private void AutoControl_Click_1(object sender, EventArgs e)//菜单-算法分析-自动分析
{
acf = new Form1();
acf.ShowEvent += new Form1.SelfeEntrust(SelfFunction);
acf.Show();
}
void SelfFunction()
{
System.out.println("HelloWorld");
}
}
在Form2中触发委托事件,执行acf.Show();
时,按下Form1中的btn_Confirm按钮则实际执行Form2中的SelfFunction函数。
补充
在同一个类中使用委托事件。
namespace ElectronicNose
{
public partial class MainForm : Form{
public delegate void SelfeEntrust(); //不同阶段的委托
public event SelfeEntrust ShowEvent; //定义一个事件
private void MainForm_Load(object sender, EventArgs e){
function2();
}
}
void function1(){
System.out.println("HelloWorld");
}
void function2(){
this.ShowEvent += new SelfeEntrust(function1);
........
........
//绑定委托
this.ShowEvent -= new SelfeEntrust(function1);
//接触委托
}