创建两个窗体,分别为form1,form2,在form1中添加控件textBox1和button1,创建一个form2的对象Form2 b = null; 在form2中添加button1,定义委托和事件 //定义委托 public delegate void MyDelegate(); //定义事件 public event MyDelegate MyEvent; 给form2中的button1添加消息相应函数并做修改 private void button1_Click(object sender, EventArgs e) { if (MyEvent != null) MyEvent();//引发事件 this.Close(); } 在form1的代码中添加函数 void b_MyEvent() { this.textBox1.Text += "已单击b窗体按钮\r\n"; } 修改form1的构造函数 public Form1() { InitializeComponent(); b = new Form2();//实例化b窗体 b.MyEvent += new Form2.MyDelegate(b_MyEvent);//监听b窗体事件 } 为form1中的button1添加消息响应函数 private void button1_Click(object sender, EventArgs e) { b.ShowDialog();
} 这样当单击form1中的按钮时会弹出form2,当单击form2中的按钮时,form1中的textbox1会显示“已单击b窗体按钮”。 具体代码如下(vs 2005实现):
form1代码:
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Text; using System.Windows.Forms;
namespace form1 {
public partial class Form1 : Form { Form2 b = null;
public Form1() { InitializeComponent();
b = new Form2();//实例化b窗体 b.MyEvent += new Form2.MyDelegate(b_MyEvent);//监听b窗体事件 }
void b_MyEvent() { this.textBox1.Text += "已单击b窗体按钮\r\n"; }
private void button1_Click(object sender, EventArgs e) { b.ShowDialog();
} } }
form2代码:
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Text; using System.Windows.Forms;
namespace form1 { public partial class Form2 : Form { public Form2() { InitializeComponent(); } //定义委托 public delegate void MyDelegate(); //定义事件 public event MyDelegate MyEvent;
private void button1_Click(object sender, EventArgs e) { if (MyEvent != null) MyEvent();//引发事件 this.Close(); }
} }
文章来源:http://blog.163.com/liujiyun123@126/blog/static/4459677620108295850128/
