1、在“窗体2”中声明事件
public delegate void Change();
public event Change myChangeevent;2、编写按钮单击事件
myChangeevent();//执行事件
3、在“窗体1”中声明“窗体2”的事件,并编写事件处理函数来处理“窗体1”的控件和内容
按钮单击函数
Form2 f = new Form2();
f.Show(); f.myChangeevent += new Form2.Change(f_myChangeevent);事件处理函数
void f_myChangeevent()
{ //throw new NotImplementedException(); textBox1.Text = "事件执行成功"; }完整的程序代码:
Form1:
1 using System; 2 using System.Collections.Generic; 3 using System.ComponentModel; 4 using System.Data; 5 using System.Drawing; 6 using System.Linq; 7 using System.Text; 8 using System.Windows.Forms; 9 10 namespace Test跨窗体 11 { 12 public partial class Form1 : Form 13 { 14 public Form1() 15 { 16 InitializeComponent(); 17 } 18 19 private void button1_Click(object sender, EventArgs e) 20 { 21 Form2 f = new Form2(); 22 f.Show(); 23 f.myChangeevent += new Form2.Change(f_myChangeevent); 24 }void f_myChangeevent() 25 { 26 //throw new NotImplementedException(); 27 textBox1.Text = "事件执行成功"; 28 } 29 } 30 }
Form2:
1 using System; 2 using System.Collections.Generic; 3 using System.ComponentModel; 4 using System.Data; 5 using System.Drawing; 6 using System.Linq; 7 using System.Text; 8 using System.Windows.Forms; 9 10 namespace Test跨窗体 11 { 12 public partial class Form2 : Form 13 { 14 public Form2() 15 { 16 InitializeComponent(); 17 } 18 public delegate void Change(); 19 public event Change myChangeevent; 20 public Change myChange; 21 private void button1_Click(object sender, EventArgs e) 22 { 23 //myChange = new Change(Print); 24 //this.Invoke(myChange);//执行委托 25 myChangeevent();//执行事件 26 } 27 private void Print() 28 { 29 button1.Text = "委托执行"; 30 } 31 } 32 }
委托和事件的最大区别在于:委托可以在任意时刻调用处理函数,而事件只能在固定的出发了当前事件时才能调用。