天天看点

c#子窗口调用主窗口控件

原文链接:https://blog.csdn.net/irwin_chen/article/details/7430524

有时子窗体的操作需要实时调用父窗体中的控件操作,比如在父窗体的文本框中显示子窗体中的输出:

c#子窗口调用主窗口控件

主窗体:

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);
    }
}
           
c#