2014-02-28 177 views

回答

5

您可以将事件处理程序添加到第一个窗体中的form_closing事件中并相应地进行处理。

某处form1

form2.Form_Closing += yourhandler; 
+0

实际上,当第二个窗体关闭时,我试图调用第一个窗体的调用方法。 –

+0

@AmritPal这是*完全*这是做什么。 – Servy

+0

@AmritPal史蒂夫的解决方案将工作。如果将上面的代码放在第一个窗体中,它会在第二个窗体关闭时调用 – MikeH

0

传递从你的第一个形式引用到你的第二个。说你创建你的第二个表格这种方式(从你的第一种形式):

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

在你的第二个形式,你应该有这样的:

public Form1 referenceToFirstForm 

然后在你OnClosing事件中,你可以参考referenceToFirstForm

+0

为什么要经历所有额外的工作,大大增加了表单的耦合性,增加了额外的脆弱性,当您可以恰当地使用事件并从应该处理的地方附加事件,而不是从定义它的类中。 – Servy

+0

只是提供选项。史蒂夫的解决方案更好。 – MikeH

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(); 
     } 
    } 
}