事件
Form1中:一个lable1用来接受Form2中textbox1的信息,button1用来show出Form2 Form1中代码: using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Text; using System.Windows.Forms; namespace WinTest { public partial class Form1 : Form { public Form1() { InitializeComponent(); } private void button1_Click(object sender, EventArgs e) { //单击该按钮时SHOW出第二个窗体 Form2 fm2 = new Form2(); fm2.myevent += new Form2.mydelegate(givevalue);//在SHOW出窗体的同时订阅FORM2的事件,调用givevalue()方法. fm2.ShowDialog(); } public void givevalue(string text) //用于修改label的方法 { this.label1.Text = text; } } } 1 Form2中:一个textbox1用来输入要传递的值,button1用来触发传递事件
Form2代码: using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Text; using System.Windows.Forms; namespace WinTest { public partial class Form2 : Form { public delegate void mydelegate(string text);//定义一个委托 public event mydelegate myevent;//定义上诉委托类型的事件 public Form2() { InitializeComponent(); } private void button1_Click(object sender, EventArgs e) { //在单击该窗体上的按钮时触发事件 if (myevent != null) { myevent(textBox1.Text); } } } }