|
C#里面可以不用自定义消息这么复杂的方法来实现跨窗体调用控件,C#有更好的办法就是委托。效果描述:有两个窗体,FORM1(一个名为“打开form2”的button控件)和FORM2(一个名为“改变form1颜色“的button控件)。启动时,FORM1中点击button控件“打开form2””使FORM2显示出来。点击FORM2中的“改变form1颜色”后,Form1中颜色改变。
一、在Form2里面:
首先声明一个委托和委托实例
Form2类外
- public delegate void ChangeFormColor(bool topmost);
public delegate void ChangeFormColor(bool topmost); Form2类里
- public event ChangeFormColor ChangeColor;
public event ChangeFormColor ChangeColor; Form2的按钮事件中调用委托
- private void button1_Click(object sender, EventArgs e)
- {
- ChangeColor(true);//执行委托实例
- }
private void button1_Click(object sender, EventArgs e) { ChangeColor(true);//执行委托实例 }
二、在Form1里面:
button控件“打开form2“的click事件中有下面的代码:
- {
- Form2 f = new Form2();
- f.ChangeColor += new ChangeFormColor(f_ChangeColor);
- f.Show();
- }
{ Form2 f = new Form2(); f.ChangeColor += new ChangeFormColor(f_ChangeColor); f.Show(); } f.ChangeColor += new ChangeFormColor(f_ChangeColor);
这句最关键,你输入到+=之后,按两下Tab,他会自动给你生成回调函数,如下:
- void f_ChangeColor(bool topmost)
- {
- this.BackColor = Color.LightBlue;
- this.Text = "改变成功";
- }
void f_ChangeColor(bool topmost) { this.BackColor = Color.LightBlue; this.Text = "改变成功"; }
三、完整代码
- using System;
- using System.Drawing;
- using System.Windows.Forms;
-
- namespace 跨窗体调用控件
- {
- public partial class Form1 : Form
- {
- public Form1()
- {
- InitializeComponent();
- }
- private void button1_Click(object sender, EventArgs e)
- {
- Form2 f = new Form2();
- f.ChangeColor += new ChangeFormColor(f_ChangeColor);
- f.Show();
- }
- void f_ChangeColor(bool topmost)
- {
- this.BackColor = Color.LightBlue;
- this.Text = "改变成功";
- }
- }
- }
using System;using System.Drawing;using System.Windows.Forms;namespace 跨窗体调用控件{ public partial class Form1 : Form { public Form1() { InitializeComponent(); } private void button1_Click(object sender, EventArgs e) { Form2 f = new Form2(); f.ChangeColor += new ChangeFormColor(f_ChangeColor); f.Show(); } void f_ChangeColor(bool topmost) { this.BackColor = Color.LightBlue; this.Text = "改变成功"; } }}
- using System;
- using System.Windows.Forms;
-
- namespace 跨窗体调用控件
- {
- public delegate void ChangeFormColor(bool topmost);
- public partial class Form2 : Form
- {
- public Form2()
- {
- InitializeComponent();
- }
- public event ChangeFormColor ChangeColor;
- private void button1_Click(object sender, EventArgs e)
- {
- ChangeColor(true);//执行委托实例
- }
- }
- }
|
|