原文地址 http://blog.csdn.net/bdstjk/article/details/7004035
FORM1(一个名为“打开form2”的button控件)
FORM2(一个名为“改变form1颜色“的button控件)
启动时,FORM1中点击button控件“打开form2””使FORM2显示出来。
点击FORM2中的“改变form1颜色”后,Form1中颜色改变。
完整代码
1 using System; 2 using System.Collections.Generic; 3 using System.ComponentModel; 4 using System.Data; 5 using System.Drawing; 6 using System.Linq; 7 using System.Text; 8 using System.Windows.Forms; 9 10 namespace Delegate 11 { 12 public delegate void ChangeFormColor(bool topmost); //声明委托和委托实例 13 public partial class Form2 : Form 14 { 15 public Form2() 16 { 17 InitializeComponent(); 18 } 19 20 public event ChangeFormColor ChangeColor; 21 22 private void button1_Click(object sender, EventArgs e) 23 { 24 ChangeColor(true); //执行委托实例 25 } 26 } 27 }
1 using System; 2 using System.Collections.Generic; 3 using System.ComponentModel; 4 using System.Data; 5 using System.Drawing; 6 using System.Linq; 7 using System.Text; 8 using System.Windows.Forms; 9 10 namespace Delegate 11 { 12 public partial class Form1 : Form 13 { 14 public Form1() 15 { 16 InitializeComponent(); 17 } 18 19 private void button1_Click(object sender, EventArgs e) 20 { 21 Form2 f = new Form2(); 22 f.ChangeColor += new ChangeFormColor(f_ChangeColor); 23 f.Show(); 24 } 25 26 void f_ChangeColor(bool topmost) 27 { 28 this.BackColor = Color.LightBlue; 29 this.Text = "改变成功"; 30 } 31 } 32 }
一、在Form2里面:
首先声明一个委托和委托实例
Form2类外
1 public delegate void ChangeFormColor(bool topmost);
Form2类里
1 public event ChangeFormColor ChangeColor;
Form2的按钮事件中调用委托
1 private void button1_Click(object sender, EventArgs e) 2 { 3 ChangeColor(true);//执行委托实例 4 }
二、在Form1里面:
button控件“打开form2“的click事件中有下面的代码:
1 { 2 Form2 f = new Form2(); 3 f.ChangeColor += new ChangeFormColor(f_ChangeColor); 4 f.Show(); 5 }
f.ChangeColor += new ChangeFormColor(f_ChangeColor);
这句最关键,你输入到+=之后,按两下Tab,他会自动给你生成回调函数,如下:
1 void f_ChangeColor(bool topmost) 2 { 3 this.BackColor = Color.LightBlue; 4 this.Text = "改变成功"; 5 }
一、在Form2里面:
首先声明一个委托和委托实例
Form2类外
- public delegate void ChangeFormColor(bool topmost);
Form2类里
- public event ChangeFormColor ChangeColor;
Form2的按钮事件中调用委托
- private void button1_Click(object sender, EventArgs e)
- {
- ChangeColor(true);//执行委托实例
- }