有時子表單的操作需要即時調用父表單中的控制項操作,比如在父表單的文字框中顯示子表單中的輸出:
主表單:
[csharp] view plaincopy
- MainForm.cs:
-
- public partial class MainForm : Form
- {
- public MainForm()
- {
- InitializeComponent();
- }
-
- private void button1_Click(object sender, EventArgs e)
- {
- SubForm SubForm = new SubForm();
-
- // 3.將ChangeTextVal加入到委託事件中
- // 等效於:
- // SubForm.ChangeTextVal += ChangeTextVal;
- SubForm.ChangeTextVal += new DelegateChangeTextVal(ChangeTextVal);
- SubForm.ShowDialog();
- }
-
- public void ChangeTextVal(string TextVal)
- {
- this.textBox1.Text = TextVal;
- }
- }
子表單:
[csharp] view plaincopy
- SubForm.cs:
-
- // 1.定義委託類型
- public delegate void DelegateChangeTextVal(string TextVal);
-
- public partial class SubForm : Form
- {
- // 2.定義委託事件
- public event DelegateChangeTextVal ChangeTextVal;
-
- public SubForm()
- {
- InitializeComponent();
- }
-
- private void button1_Click(object sender, EventArgs e)
- {
- ChangeMainFormText(this.textBox1.Text);
- }
-
- private void ChangeMainFormText(string TextVal)
- {
- // 4.調用委託事件函數
- ChangeTextVal(TextVal);
- }
- }