C# 窗体间操作 委托

 1 using System;
 2 using System.Windows.Forms;
 3 namespace 窗体间操作_委托
 4 {
 5     public partial class frm1 : Form
 6     {
 7         frm2 f2 = new frm2();
 8         public frm1()//在窗体初始化时...
 9         {
10             InitializeComponent();
11             f2.Action = this.Action_frm1;//4.给委托变量指向Action_frm1方法
12             f2.Show();//显示窗体2
13         }
14         private void Action_frm1(string str)//2.为委托创建一个方法
15         {
16             lb_frm1.Text = str;
17         }
18 
19         private void frm1_Load(object sender, EventArgs e)
20         {
21             lb_frm1.Text = string.Empty;
22         }
23 
24         private void button2_Click(object sender, EventArgs e)
25         {
26             if (txt_frm1.Text.Length <= 0) return;           
27             f2.Action_frm2(txt_frm1.Text);//6.调用窗体2中的方法。
28         }
29     }
30     public delegate void ActionDelegate(string str);//1.定义一个委托
31 }
frm1
 1 using System;
 2 using System.Windows.Forms;
 3 namespace 窗体间操作_委托
 4 {
 5     public partial class frm2 : Form
 6     {
 7         public ActionDelegate Action;//3.定义一个委托变量
 8         public frm2()
 9         {
10             InitializeComponent();
11         }
12 
13         private void button1_Click(object sender, EventArgs e)
14         {
15             if (this.txt_frm2.Text.Length <= 0) return;
16             Action(txt_frm2.Text);
17         }
18 
19         private void frm2_Load(object sender, EventArgs e)
20         {
21             lb_frm2.Text = string.Empty;
22         }
23 
24         public void Action_frm2(string str)//5.定义一个方法,供其他窗体调用。
25         {
26             this.lb_frm2.Text = str;
27         }
28     }
29 }
frm2

 

posted @ 2020-04-15 09:09  潇湘梦白  阅读(300)  评论(0)    收藏  举报