原文連結:https://blog.csdn.net/irwin_chen/article/details/7430524
有時子窗體的操作需要實時調用父窗體中的控件操作,比如在父窗體的文本框中顯示子窗體中的輸出:

主窗體:
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;
}
}
子窗體:
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);
}
}