[C# 学习]窗体间调用控件
时间:2014-05-11 15:25:46
收藏:0
阅读:511
一、方法1:
假如有两个窗体,Form_A和Form_B,每个窗体里都有一个按键,Button_A和Button_B,要实现单击Button_A显示窗体B,那么窗体A中Buttom_A的单击事件的程序应该是:
private void button_A_Click(object sender, EventArgs e) { Form_B f = new Form_B(); f.Show(); }
如果希望单击窗体B中的按键Button_B,实现改变窗体A的背景色,那么你需要做:
1. Form_B 窗体的Class里添加如下代码:
public Form_A fb; public Form_B(Form_A f) { InitializeComponent(); fb = f; } private void button_B_Click(object sender, EventArgs e) { fb.BackColor = Color.Brown; }
2. Form_A窗体中的Button_A单击事件变成:
private void button_A_Click(object sender, EventArgs e) { Form_B f = new Form_B(this); f.Show(); }
完整程序如下
Form_A:
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 formExam { public partial class Form_A : Form { public Form_A() { InitializeComponent(); } private void Button_A_Click(object sender, EventArgs e) { Form_B f = new Form_B(this); f.Show(); } private void Form_A_Load(object sender, EventArgs e) { } } }
Form_B:
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 formExam { public partial class Form_B : Form { public Form_A fb; public Form_B(Form_A f) { InitializeComponent(); fb = f; } private void Button_B_Click(object sender, EventArgs e) { fb.BackColor = Color.Brown; } } }
二、方法2:通过委托实现
1. 在Form_B的Class外定义一个委托类型
public delegate void ChangeFormColor();
2. 在Form_B的Class内定义委托的方法
public event ChangeFormColor ChangeColor;
3. Button_B单击事件为
private void Button_B_Click(object sender, EventArgs e) { ChangeColor(); }
4. Form_A中的单击事件为
private void Button_A_Click(object sender, EventArgs e) { Form_B f = new Form_B(); f.ChangeColor += new ChangeFormColor(f_ChangeColor); f.Show(); }
5. 编写改变Form_A 背景色的方法
void f_ChangeColor() { this.BackColor = Color.Brown; }
完整程序如下:
Form_A:
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 formExam { public partial class Form_A : Form { public Form_A() { InitializeComponent(); } private void Button_A_Click(object sender, EventArgs e) { Form_B f = new Form_B(); f.ChangeColor += new ChangeFormColor(f_ChangeColor); f.Show(); } void f_ChangeColor() { this.BackColor = Color.Brown; } } }
Form_B:
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 formExam { public delegate void ChangeFormColor(); public partial class Form_B : Form { public event ChangeFormColor ChangeColor; public Form_B() { InitializeComponent(); } private void Button_B_Click(object sender, EventArgs e) { ChangeColor(); } } }
评论(0)