winform使用委托和事件来完成两个窗体之间通信的实例
单击按钮
/// <summary>
/// Form1
/// </summary>
/// <param name="message"></param>
public delegate void ClickDelegateHander(string message); //声明一个委托
public partial class Form1 : Form
{
public event ClickDelegateHander ClickEvent;//声明一个事件
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
if (ClickEvent != null) //判断事件是否被注册
ClickEvent("Hello World");
}
}
/// <summary>
/// Form2
/// </summary>
public partial class Form2 : Form
{
public Form2()
{
InitializeComponent();
Form1 form1 = new Form1();
form1.ClickEvent += new ClickDelegateHander(getMessage);//注册事件
form1.Show();
}
private void Form2_Load(object sender, EventArgs e)
{
}
public void getMessage(string message)
{
this.label1.Text = message;
}
}
把Form2设为启动项