標籤:style blog class code java tar
一、方法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(); } }}