2014-02-28 169 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(); 
     } 
    } 
}