2013-03-31 175 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

相关问题