我在关闭菜单表单时尝试关闭我的应用程序。 这是我的代码:
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;
}
}
关闭此消息时会出现两次。
答案 0 :(得分:4)
您不必再次退出,只需让它通过:
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;
}
}
答案 1 :(得分:2)
您可以覆盖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;
}
}
}
或者在关于在班级中使用bool(例如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();
}
答案 2 :(得分:1)
您收到两条消息,因为Application.Exit();
正在关闭frmMenu
,而您正在关闭它=> frmMenu
关闭两次。
如果frmMenu
是您的应用程序的主要形式,这意味着您应该在 Program.cs 文件中有类似的内容:
static class Program {
[STAThread]
static void Main() {
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Application.Run(new FrmMenu());
}
}
...然后关闭frmMenu
时应用程序将退出。如 derape 所述,您无需致电Application.Exit()
答案 3 :(得分:0)
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;
}
}