1)目标
父窗口与子窗口都有1个Button和1个Label。
目标1:单击父窗口的Button,子窗口的Label将显示父窗口传来的值。
目标2:单击子窗口的Button,父窗口的Label将显示子窗口传来的值。
2)父窗口代码
using System; using System.Threading.Tasks; using System.Windows.Forms; namespace WindowsFormsApp5 { public delegate void ShowMessageService(string msg); public partial class FormMain : Form { private FormChild childForm = new FormChild(); public FormMain() { InitializeComponent(); } private void FormMain_Load(object sender, EventArgs e) { childForm.showMessageChild = new ShowMessageService(UpdateLabel); childForm.Show(); } public async void UpdateLabel(string msg) { await Task.Delay(2000); this.label1.Text = msg; } private void button1_Click(object sender, EventArgs e) { ShowMessageService sms = new ShowMessageService(childForm.UpdateLabel); this.BeginInvoke(sms, "Message from FormMain"); } } }
3)子窗口代码
using System; using System.Threading.Tasks; using System.Windows.Forms; namespace WindowsFormsApp5 { public partial class FormChild : Form { public ShowMessageService showMessageChild; public FormChild() { InitializeComponent(); } public async void UpdateLabel(string msg) { await Task.Delay(2000); this.label1.Text = msg; } private void button1_Click(object sender, EventArgs e) { this.BeginInvoke(showMessageChild, "Message from FormChild"); } } }
4)解释
4.1)定义委托
public delegate void ShowMessageService(string msg);
4.2)父窗口向子窗口传递消息
①由于父窗口拥有子窗口对象,所以直接利用子窗口的方法来创建委托对象,然后用this.BeginInvoke进行异步调用。
private void button1_Click(object sender, EventArgs e)
{
ShowMessageService sms = new ShowMessageService(childForm.UpdateLabel);//定义委托对象,指向子窗口的UpdateLabel方法。
this.BeginInvoke(sms, "Message from FormMain"); //执行的是子窗口的UpdateLabel方法
}
4.3)子窗口向父窗口传递消息
①子窗口声明委托对象
public partial class FormChild : Form
{
public ShowMessageService showMessageChild;//声明
}
②在主窗口给委托对象赋值。
public partial class FormMain : Form
{
private FormChild childForm = new FormChild();
private void FormMain_Load(object sender, EventArgs e)
{
childForm.showMessageChild = new ShowMessageService(UpdateLabel); //子窗口的委托对象指向父窗口的UpdateLabel方法。
childForm.Show();
}
}
③子窗口用this.BeginInvoke进行异步调用。
private void button1_Click(object sender, EventArgs e)
{
this.BeginInvoke(showMessageChild, "Message from FormChild");
}
原文地址:https://www.cnblogs.com/wyvern0618/p/9442381.html