winform使用委托和事件来完成两个窗体之间通信的实例
发布时间:2016-12-28 来源:查字典编辑
摘要:单击按钮复制代码代码如下://////Form1//////publicdelegatevoidClickDelegateHander(st...
单击按钮
复制代码 代码如下:
/// <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设为启动项