从另一个窗口调用方法来关闭事件。 C#

时间:2014-02-28 17:22:01

标签: c# .net winforms c#-4.0 window

如何从另一个表单关闭事件中调用窗口表单的方法? 假设第二个是关闭,我想在第二个关闭时调用第一个表单的方法来更新第一个窗口表单上的一些更改。

3 个答案:

答案 0 :(得分:5)

您可以在第一个表单中为form_closing事件添加事件处理程序并相应地处理它。

form1

中的某个地方
form2.Form_Closing += yourhandler;

答案 1 :(得分:1)

这假定表单2有一个名为TextBox1的控件,当表单2关闭时,将调用lambda表达式并将数据传输到表单1。

public partial class Form1 : Form
{

    private Form2 openedForm2 = null;

    public Form1()
    {
        InitializeComponent();
    }

    private void button1_Click(object sender, EventArgs e)
    {
        // Not sure if you would want more than 1 form2 open at a time.
        if (this.openedForm2 == null)
        {
            this.openedForm2 = new Form2();
            //Here is your Event handler which accepts a Lambda Expression, code inside is performed when the form2 is closed.
            this.openedForm2.FormClosing += (o, form) =>
            {
                // this is Executed when form2 closes.
                // Gets text from Textbox1 on form2 and assigns its value to textbox1 on form 1
                this.textBox1.Text = ((Form2)o).Controls["TextBox1"].Text;
                // Set it null so you can open a new form2 if wanted.
                this.openedForm2 = null;
            };
            this.openedForm2.Show();
        }
        else 
        {
            // Tells user form2 is already open and focus's it for them.
            MessageBox.Show("Form 2 is already open");
            this.openedForm2.Focus();
        }
    }
}

答案 2 :(得分:0)

将您的第一张表格中的参考传递给您的第二张表格。假设您以这种方式创建第二个表单(从您的第一个表单):

Form2 frm2 = new Form2();
frm2.referenceToFirstForm = this

在你的第二种形式中你应该有这个:

public Form1 referenceToFirstForm

然后在您的OnClosing活动中,您可以参考referenceToFirstForm