創建兩個窗體,分別為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/