目標:在子窗口Form2上單擊按鈕時向Form1傳遞一組自定義參數,並顯示在父窗口Form1上。
方法:有很多方法,這裡只介紹委托和事件的實現方式。
思路:Form2中定義事件,Form1創建Form2並訂閱事件;Form2觸發事件後傳遞參數到Form1,Form1處理參數。
Form1代碼如下:
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 FormDataInteractive { /// <summary> /// powered by shadu {at} foxmail.com /// </summary> public partial class Form1 : Form { public Form1() { InitializeComponent(); } private void button1_Click(object sender, EventArgs e) { // 創建Form2,並添加事件處理函數 Form2 frm = new Form2(); frm.DataChange += new Form2.DataChangeHandler(DataChanged); frm.ShowDialog(); } public void DataChanged(object sender, DataChangeEventArgs args) { // 更新窗體控件 textBox1.Text = args.name; textBox2.Text = args.pass; } } }
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 FormDataInteractive { public partial class Form2 : Form { // 定義委托 // public delegate void DataChangeHandler(string x); 一次可以傳遞一個string public delegate void DataChangeHandler(object sender, DataChangeEventArgs args); // 聲明事件 public event DataChangeHandler DataChange; // 調用事件函數 public void OnDataChange(object sender, DataChangeEventArgs args) { if (DataChange != null) { DataChange(this, args); } } public Form2() { InitializeComponent(); } private void button1_Click(object sender, EventArgs e) { // 觸發事件, 傳遞自定義參數 OnDataChange(this, new DataChangeEventArgs(textBox1.Text, textBox2.Text)); } } /// <summary> /// 自定義事件參數類型,根據需要可設定多種參數便於傳遞 /// </summary> public class DataChangeEventArgs : EventArgs { public string name { get; set; } public string pass { get; set; } public DataChangeEventArgs(string s1, string s2) { name = s1; pass = s2; } } }
實驗效果: