2013-03-31 126 views
0

當'X'被點擊時,我的程序並不退出,所以當我查看時,我得到了這段代碼。用窗口'X'按鈕關閉窗體

protected override void OnFormClosing(FormClosingEventArgs e) 
    { 
     Application.Exit(); 
    } 

但這會干擾this.Close()方法。

當單擊'X'而不是當表單實際關閉時,是否有一種方法可以使用此代碼?這似乎是唯一有問題的表單?

using System; 
using System.Collections.Generic; 
using System.ComponentModel; 
using System.Data; 
using System.Drawing; 
using System.Linq; 
using System.Text; 
using System.Windows.Forms; 

namespace PassMan 
{ 
public partial class Passwords : Form 
{ 
    String[,] UandS = { { "Russell", "Hickey" }, { "Junior", "Russ" } }; 
    public Passwords() 
    { 
     InitializeComponent(); 
     for (int i = 0; i < UandS.Length/2; i++) 
     { 
      for (int j = 0; j < 2; j++) 
      { 
       if (j % 2 == 0) 
       { 
        tbUsernames.Text = tbUsernames.Text + UandS[i, j] + "\r\n"; 
       } 
       else 
       { 
        tbPasswords.Text = tbPasswords.Text + UandS[i, j] + "\r\n"; 
       } 
      } 
     } 
     tbPasswords.PasswordChar = '*'; 
    } 

    private void btnSH_Click(object sender, EventArgs e) 
    { 
     Properties.Settings.Default.Save(); 
     if (btnSH.Text == "Show Passwords") 
     { 
      btnSH.Text = "Hide Passwords"; 
      tbPasswords.PasswordChar = (char)0; 
     } 
     else 
     { 
      btnSH.Text = "Show Passwords"; 
      tbPasswords.PasswordChar = '*'; 
     } 
    } 
    private void btnClose_Click(object sender, EventArgs e) 
    { 
     Application.Exit(); 
    } 

    private void btnLogin_Click(object sender, EventArgs e) 
    { 
     fLogin main = new fLogin(); 
     main.Show(); 
     this.Close(); 
    } 

    protected override void OnFormClosing(FormClosingEventArgs e) 
    { 
     //Application.Exit(); 
    } 

} 

}

+0

你能分享更多的代碼? – scartag

+0

你的問題可能是很不清楚的。請將它放在OnFormClosed()中,以避免再次入侵問題。 –

+0

代碼更新,出於某種原因它只是在這種形式? – Dobz

回答

2

該方法接收的FormClosingEventArgs參數。在這樣的說法存在CloseReason財產

CloseReason屬性解釋爲什麼形式正在關閉....

一個表單可以因爲各種原因被關閉,既 用戶發起和方案。 CloseReason屬性指示關閉的原因 。

你可以檢查這個屬性,看它是否是

UserClosing - 用戶通過用戶界面 (UI)封閉形式,例如通過點擊關閉按鈕窗口窗口, 從窗口的控制菜單中選擇關閉,或者按下ALT + F4。

ApplicationExitCall - 調用應用程序類的Exit方法爲 。其他

原因關閉事件在上述

的鏈接解釋所以,如果我理解正確的話你的意圖,你可以寫

protected override void OnFormClosing(FormClosingEventArgs e) 
{ 
    if(e.CloseReason == CloseReason.UserClosing) 
     Application.Exit(); 
    else 
     // it is not clear what you want to do in this case ..... 
} 
+0

完美工作!謝謝! – Dobz