2013-05-09 42 views
0

在我的應用程序幾次我必須調用一個窗口(類)。這個窗口的工作是顯示一個單詞的含義。當我再次呼叫該窗口時,會顯示一個新窗口,但前一個窗口也會顯示。我有兩個表格form1,form2如果被調用的窗口已經在運行,然後關閉它並運行新調用的窗口

Form1中就是這樣:

public partial class Form1 : Form 
{ 
    public Form1() 
    { 
     InitializeComponent(); 
    } 

    private void button1_Click(object sender, EventArgs e) 
    { 
     string a = textBox1.Text; 
     Form2 s = new Form2(a);// it will be called as many time as i click 
     s.Show(); 
    } 
} 

Form2的是這樣的:

public partial class Form2 : Form 
{ 
    public Form2(string s) 
    { 
     InitializeComponent(); 
     label1.Text = s; 
    } 
} 

我想是這裏面Form1中如果我叫窗口2就說明,但如果我再次調用窗口2之前的窗口2窗口將自動關閉,新的form2窗口將顯示而不是前一個窗口。 我該怎麼做?

+2

不要創建每次一個新窗口((X)''新show_meaning),並顯示相同的表單實例。 – I4V 2013-05-09 08:07:19

+0

+1 @ l4v。將引用單詞含義表單存儲爲類級變量,並在每次需要時引用它。 – Adrian 2013-05-09 08:11:10

+1

並使用FormClosed事件來知道該窗口已被用戶關閉,並將該參考設置回null。 – 2013-05-09 09:52:58

回答

1

這裏是存放在一流水平的窗體2參考的例子,如已在其他人所說:

public partial class Form1 : Form 
{ 

    private Form2 f2 = null; 

    public Form1() 
    { 
     InitializeComponent(); 
    } 

    private void button1_Click(object sender, EventArgs e) 
    { 
     if (f2 != null && !f2.IsDisposed) 
     { 
      f2.Dispose();  
     } 

     string a = textBox1.Text; 
     f2 = new Form2(a); 
     f2.Show(); 
    } 

} 
+0

我想要的是,如果我打電話form2它內部form1它顯示,但如果我再次調用form2以前的form2窗口將自動關閉和新的form2窗口將顯示,而不是以前的 – DarkenShooter 2013-05-09 15:31:33

+0

Gotcha ...誤讀了這個問題。代碼已更新。 – 2013-05-09 15:35:48

0

我認爲你應該考慮使用單例模式。

你可以這樣實現它:

public partial class Form1 : Form 
{ 
    public Form1() 
    { 
     InitializeComponent(); 
    } 

    private void button1_Click(object sender, EventArgs e) 
    { 
     string a = textBox1.Text; 
     Form2.ShowMeaning(a);// it will be called as many time as you click 
    } 
} 

1和Form 2

public partial class Form2 : Form 
{ 
    private static readonly Form2 _formInstance = new Form2(); 

    private Form2() 
    { 
     InitializeComponent(); 
    } 

    private void LoadMeaning(string s) 
    { 
     label1.Text = s; 
    } 

    //Override method to prevent disposing the form when closing. 
    protected override void OnClosing(CancelEventArgs e) 
    { 
     e.Cancel = true; 
     this.Hide(); 
    } 

    public static void ShowMeaning(string s) 
    { 
     _formInstance.LoadMeaning(s); 
     _formInstance.Show(); 
    } 
} 

希望它能幫助。

+0

看我有2個窗體名爲form1,form2。在form1中「show_meaning s = new show_meaning(x); s.Show();」被稱爲多次,因爲我想。但show_meaning(x)是insid form2.can你給任何簡單的方法呢? @VahidND – DarkenShooter 2013-05-09 13:53:25

+0

您對show_meaning()的定義沒有定義返回值,所以我將其視爲構造函數。爲了更好地理解,我重命名方法以匹配您的命名,但如果您爲form2提供完整代碼,我可能會進一步幫助您。 – VahidNaderi 2013-05-09 14:59:28

+0

我編輯了我的問題。請看看。@ VahidND – DarkenShooter 2013-05-09 15:06:19

相關問題