有时子窗体的操作需要实时调用父窗体中的控件操作,比如在父窗体的文本框中显示子窗体中的输出:
主窗体:
- 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);
- }
- }