在线时间:8:00-16:00
迪恩网络APP
随时随地掌握行业动态
扫描二维码
关注迪恩网络微信公众号
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) 4.3)子窗口向父窗口传递消息 ①子窗口声明委托对象 public partial class FormChild : Form public ShowMessageService showMessageChild;//声明 } ②在主窗口给委托对象赋值。 public partial class FormMain : Form } ③子窗口用this.BeginInvoke进行异步调用。 private void button1_Click(object sender, EventArgs e)
|
请发表评论