父窗体:Form1 ,有个 textbox1.text ,有个button1
子窗体:Form2 ,有个 textbox1.text ,有个button1
修改Form1 的textbox1.text ,点击Form1的 button1,弹出Form2,点击Form2 的button ,结果:Form2的 textbox1.text 的值为 Form1的textbox1.text ,修改下 Form1的textbox1.text ,再点Form2 的button ,Form2的 textbox1.text 的值与Form1的 textbox1.text 保持一致
首先在Form2中定义委托和事件:
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 TestDelegate { public partial class Form2 : Form { public Form2() { InitializeComponent(); } private void Form2_Load(object sender, EventArgs e) { } public delegate string TransfDelegate(); //委托的方法体必须返回值为string,无参数 public event TransfDelegate TransfEvent; private void button1_Click(object sender, EventArgs e) { textBox1.Text = TransfEvent(); } } }
然后在Form1中进行调用:
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 TestDelegate { public partial class Form1 : Form { public Form1() { InitializeComponent(); } private void Form1_Load(object sender, EventArgs e) { } private void button1_Click(object sender, EventArgs e) { Form2 frm = new Form2(); //注册事件 frm.TransfEvent += GetValueEvent; frm.Show(); } string GetValueEvent() { return textBox1.Text; } } }