[WinForm]委托应用①——窗口之间方法/控件调用

不传参数 
第二窗口:

public partial class Form2 : Form { /// <summary> /// 定义委托 /// </summary> public delegate void testDelegate(); /// <summary> /// 定义委托事件 /// </summary> public event testDelegate refreshForm; public Form2() { InitializeComponent(); } private void button1_Click(object sender, EventArgs e) { //执行委托事件 //具体执行的到底是什么,form2并不关心, //如果你订阅了我的refreshForm事件, //那么我执行refreshForm的时候你就必须响应 refreshForm(); this.Close(); } }

第一窗口:
 private void button1_Click(object sender, EventArgs e)
         {
             Form2 f = new Form2();
             //这里订阅Form2的refreshForm()事件,具体你怎么执行我不管,
             //我把我的RefreshForm1()绑定在了你的refreshForm()事件上,
             //不管你在何时何地执行了你的refreshForm()事件,
             //那么我的refreshForm1()事件就会跟着执行,因为我已经抱住你的大腿了!
             f.refreshForm += new Form2.testDelegate(RefreshForm1);
             f.ShowDialog();
         }
 
         public void RefreshForm1()
         {
             button1.Text = "Good job!";
         }

传递参数:----------------------------------------------------------------------------------
窗口1:

public partial class Form1 : Form
    {
        public delegate void delegateRef(int a, string b, int c);
        public Form1()
        {
            InitializeComponent();
        }
  
        private void button1_Click(object sender, EventArgs e)
        {
            delegateRef dlg = new delegateRef(Get);
            Form2 f2 = new Form2(dlg);
            f2.Show();
        }
  
        private void Get(int a, string b, int c)
        {
            label1.Text = "a=" + a + ",b=" + b + ",c=" + c;
        }
    }

窗口2:

public partial class Form2 : Form
    {
        private Form1.delegateRef dlg;
        public Form2(Form1.delegateRef dlg)
        {
            InitializeComponent();
            this.dlg = dlg;
        }
  
        private void button1_Click(object sender, EventArgs e)
        {
            this.dlg(4, "abc", 65);
        }
    }
















原文地址:https://www.cnblogs.com/liuxingleiyu/p/6178181.html