在C#裏面倒是能夠不用自定義消息這麼複雜的方法來實現跨窗體調用控件,C#有更好的辦法就是委託。函數
效果描述:有兩個窗體,FORM1(一個名爲「打開form2」的button控件)和FORM2(一個名爲「改變form1顏色「的button控件)。啓動時,FORM1中點擊button控件「打開form2」」使FORM2顯示出來。點擊FORM2中的「改變form1顏色」後,Form1中顏色改變。this
1、在Form2裏面:
首先聲明一個委託和委託實例
Form2類外spa
- public delegate void ChangeFormColor(bool topmost);
Form2類裏.net
- public event ChangeFormColor ChangeColor;
Form2的按鈕事件中調用委託orm
- private void button1_Click(object sender, EventArgs e)
- {
- ChangeColor(true);
- }
2、在Form1裏面:
button控件「打開form2「的click事件中有下面的代碼:blog
- {
- 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 = "改變成功";
- }
3、完整代碼get
- 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);
- }
- }
- }
最後再給你們介紹一種最簡單的C#跨窗體操做回調函數