標籤:blog http os ar for strong sp div 2014
C# 委託 事件 之 表單之間互傳值
效果:
Form1.cs:
using System;using System.Windows.Forms;namespace 表單事件互傳值2{ public delegate void SetTxb2Del(string str, object obj);//定製針對Txb2的委託 public partial class Form1 : Form { private event SetTxb2Del st2dEvent;//聲明Txb2委託的事件 public Form1() { InitializeComponent(); } private void button1_Click(object sender, EventArgs e) { Form2 f2 = new Form2();//執行個體化一個Form2表單 this.st2dEvent += new SetTxb2Del(f2.SetTxb2);//為事件註冊Form2中設定txb2值的方法(待執行) this.st2dEvent(txb1.Text, this);//呼叫事件(參數傳入方法SetTxb2,並執行) f2.ShowDialog();//展示表單 } /// <summary> /// 設定txb1文本的方法 /// </summary> /// <param name="str">要設定為值的字串</param> public void SetTxb1(string str) { txb1.Text = str; } }}
Form2.cs:
using System;using System.Windows.Forms;namespace 表單事件互傳值2{ public delegate void SetTxb1Del(string str);//定製針對Txb1的委託 public partial class Form2 : Form { private event SetTxb1Del st1dEvent;//聲明Txb1委託的事件 public Form2() { InitializeComponent(); } private void button1_Click(object sender, EventArgs e) { Form1 f1 = this.Tag as Form1;//從Tag屬性得到Form1對象 this.st1dEvent += new SetTxb1Del(f1.SetTxb1);//為事件註冊Form1中設定txb1值的方法(待執行) this.st1dEvent(txb2.Text);//呼叫事件(參數傳入方法SetTxb1,並執行) this.Close();//關閉視窗 } /// <summary> /// 設定txb2文本的方法 /// </summary> /// <param name="str">要設定為值的字串</param> /// <param name="obj">來源物件(Form1)</param> public void SetTxb2(string str, object obj) { txb2.Text = str;//設定文字框的值 this.Tag = obj;//暫存Form1對象到當前Form2的Tag屬性 } }}
C# 委託 事件 之 表單之間互傳值