C# 动态创建出来的窗体间的通讯 delegate1

附件 http://files.cnblogs.com/xe2011/CSharp_WindowsForms_delegate01.rar

需要每个窗体是独立存在,禁止相与引用窗体

这样干净并且可以反复重用

Form1的代码

      private void button1_Click(object sender, EventArgs e)
        {
            Form2 f2 = new Form2();
            f2.XYZ += new Form2.CallBack(GetForm2TextBox1Text);
            f2.Show();
        }

        void GetForm2TextBox1Text(string s)
        {
            textBox1.Text = s;
        }

Form2

        public delegate void CallBack(string s);
        public event CallBack XYZ;
        private void textBox1_TextChanged(object sender, EventArgs e)
        {
            XYZ(textBox1.Text);
        }

Form1的完整代码

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;

namespace WindowsFormsApplication2
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void button1_Click(object sender, EventArgs e)
        {
            Form2 f2 = new Form2();
            f2.XYZ += new Form2.CallBack(GetForm2TextBox1Text);
            f2.Show();
        }

        void GetForm2TextBox1Text(string s)
        {
            textBox1.Text = s;
        }

    }
}
Form1

Form2的完整代码

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;

namespace WindowsFormsApplication2
{
    public partial class Form2 : Form
    {
        public Form2()
        {
            InitializeComponent();
        }

        public delegate void CallBack(string s);
        public event CallBack XYZ;
        private void textBox1_TextChanged(object sender, EventArgs e)
        {
            XYZ(textBox1.Text);
        }

    }
}
Form2
原文地址:https://www.cnblogs.com/xe2011/p/3440258.html