1,共有两个窗体
主窗体代码
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; namespace 委托应用 { //主窗体接受信息委托 public delegate void ReturnText(string info); //主窗体发送信息委托 public delegate void SendText(string info); public partial class FormMain : Form { public FormMain() { InitializeComponent(); } //创建一个集合用于储存子窗体 public List<Form> forms = new List<Form>(); //根据接受委托创建方法 public void ReturnTextMethod(string info) { this.textBox1.Text = info; } //主窗体发送信息变量 public SendText sendText; //创建子窗体 private void button3_Click(object sender, EventArgs e) { //为了防止重复的建立子窗体 if (forms.Count==0) { //创建3个子窗体 for (int i = 1; i < 4; i++) { FormChild child = new FormChild(); //这里需要设置子窗体的StartPosition属性为Manual child.Location = new Point(250 * i, 200); //子窗体中的委托变量关联主窗体的方法 child.returnText += this.ReturnTextMethod; sendText += child.SendText; forms.Add(child); child.Show(); } } } //关掉所有子窗体 private void button4_Click(object sender, EventArgs e) { foreach (var item in forms) { item.Close(); } //清空集合 forms.Clear(); } //主窗体发送信息 private void button1_Click(object sender, EventArgs e) { sendText(this.textBox2.Text); } } }
子窗体代码
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; namespace 委托应用 { public partial class FormChild : Form { //子窗体发送信息变量 public ReturnText returnText; public FormChild() { InitializeComponent(); } // public void SendText(string info) { this.textBox2.Text = info; } private void button1_Click(object sender, EventArgs e) { returnText(this.textBox1.Text); } } }