C# 委托和事件 实现窗体间的通信

例子 : 点击form1上的按钮打开form2窗口,在form2窗体中的文本框中输入一个值后,在点击form2窗体中按钮,在form2中的文本框中输入的值也会在form1中的文本框中出现。

form1:

        public partial class Form1 : Form

       {
             public Form1()
            {
               InitializeComponent();
            }

            private void textBox1_TextChanged(object sender, EventArgs e)
           {

           }

            private void button1_Click(object sender, EventArgs e)
           {
               Form2 frm = new Form2();
               frm.Text_event += new Form2.Text_delegate(getData);
               frm.ShowDialog();
            }

            public void getData()
            {
                textBox1.Text = Form2.x;
             }
       }

form2:

        public partial class Form2 : Form

       {
             public Form2()
            {
               InitializeComponent();
            }

            private void Form2_Load(object sender, EventArgs e)
           {

           }

           public delegate void Text_delegate();
           public event Text_delegate Text_event;
           public static string x;

           public void Tram()
          {   
                x = textBox1.Text;
                if (Text_event != null) Text_event();
           }

           private void textBox1_TextChanged(object sender, EventArgs e)
          {

          }

          private void button1_Click(object sender, EventArgs e)
         {
               if (!String.IsNullOrEmpty(this.textBox1.Text))
                {
                    Tram();
                }
          }
}

原文地址:https://www.cnblogs.com/yanyao/p/5337485.html