winform使用委托和事件来完成两个窗体之间通信的实例
程序员文章站
2024-02-18 13:01:40
单击按钮
复制代码 代码如下:/// /// form1 ...
单击按钮
复制代码 代码如下:
/// <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设为启动项