[英]Closing application in FormClosing event
I am trying to close my application when closing the menu form. 关闭菜单表单时,我试图关闭我的应用程序。 This is my code:
这是我的代码:
private void frmMenu_FormClosing(object sender, FormClosingEventArgs e)
{
var result = MessageBox.Show("Do you want to close this application",
"Alert", MessageBoxButtons.YesNo, MessageBoxIcon.Warning);
if (result == DialogResult.Yes)
{
//this.Close();
Application.Exit();
//e.Cancel = false;
}
else
{
e.Cancel = true;
}
}
When closing this message appears twice. 关闭时,此消息出现两次。
You don't have to do the exit again, just let it pass: 您不必再次退出,只需让它通过即可:
private void frmMenu_FormClosing(object sender, FormClosingEventArgs e)
{
var result = MessageBox.Show("Do you want to close this application?",
"Alert", MessageBoxButtons.YesNo, MessageBoxIcon.Warning);
if (result == DialogResult.No)
{
e.Cancel = true;
}
}
You can override the OnFormClosing
method: 您可以重写
OnFormClosing
方法:
protected override void OnFormClosing(FormClosingEventArgs e) {
base.OnFormClosing(e);
if (!e.Cancel) {
if (MessageBox.Show("Do you want to close this application?", "Close Application", MessageBoxButtons.YesNo) != DialogResult.Yes) {
e.Cancel = true;
}
}
}
Or following Hans Passant 's advice in the comments on using a bool (eg IsDataValid
) in your class: 或者在类中使用布尔值(例如
IsDataValid
)的注释中遵循Hans Passant的建议:
private void frmMenu_FormClosing(object sender, FormClosingEventArgs e)
{
if (!IsDataValid)
{
if(DialogResult.Yes == MessageBox.Show(Do you want to close this application?",
"Alert", MessageBoxButtons.YesNo, MessageBoxIcon.Question))
this.Dispose(); //or Application.Exit();
else
e.Cancel = true;
}
else
this.Dispose(); //or Application.Exit();
}
You get two messages because Application.Exit();
您收到两条消息,因为
Application.Exit();
is closing frmMenu
, whereas you are currently closing it => frmMenu
is closed twice. 正在关闭
frmMenu
,而您当前正在关闭=> frmMenu
关闭两次。
If frmMenu
is the main form of your application, meaning you should having something like that in your Program.cs file: 如果
frmMenu
是应用程序的主要形式,则意味着在Program.cs文件中应包含类似内容:
static class Program {
[STAThread]
static void Main() {
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Application.Run(new FrmMenu());
}
}
... then the application will exit when closing frmMenu
. ...然后关闭
frmMenu
时,应用程序将退出。 As said by derape , you then don't have to call Application.Exit()
如derape所述,您不必调用
Application.Exit()
private void frmMenu_FormClosing(object sender, FormClosingEventArgs e)
{
if (MessageBox.Show("Do you want to close this application", "Alert", MessageBoxButtons.YesNo, MessageBoxIcon.Warning) == DialogResult.No)
{
e.Cancel = true;
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.