当DialogResult为否时阻止窗体closures

我正在使用下面的代码closures我的Windows窗体应用程序窗体的事件:

private void Main_FormClosing(object sender, FormClosingEventArgs e) { DialogResult dr = MessageBox.Show("Are you sure you want to quit?", "Leaving App",MessageBoxButtons.YesNo, MessageBoxIcon.Question); if (dr == DialogResult.No) { return; } else Application.Exit(); } 

但问题是,无论何时用户单击是应用程序结束,但当用户单击否,应用程序仍在运行,但窗体隐藏。 当用户点击“否”时,如何保持窗体可见?

更新

我面对的另一个问题是,当我单击是时,MessageBox再次显示,然后单击是应用程序退出。 为什么它显示两次?

您不必调用Application.Exit()因为如果您不取消关闭它,程序将退出本身。 以下是正在工作的更正的代码:

 private void Main_FormClosing(object sender, FormClosingEventArgs e) { DialogResult dr = MessageBox.Show("Are you sure you want to quit?", "Leaving App",MessageBoxButtons.YesNo, MessageBoxIcon.Question); if (dr == DialogResult.No) { e.Cancel = true; } } 
 private void Form1_Closing(Object sender, CancelEventArgs e) { if (!isDataSaved) { e.Cancel = true; MessageBox.Show("You must save first."); } else { e.Cancel = false; MessageBox.Show("Goodbye."); } } 

来源:MSDN

您需要使用e.Cancel = true;取消退出e.Cancel = true; 在你的事件Main_FormClosing停止关闭

我知道这不是正确的方式,但它会按照你的意愿。

 private void Form1_FormClosing(object sender, FormClosingEventArgs e) { if(MessageBox.Show("Are you sure you want to quit?", "Leaving App", MessageBoxButtons.YesNo).ToString()=="No") e.Cancel = true; } 

由于ToString()方法将在与消息框一起使用时提供对话框的结果。

我是Akhilavishnu,更多的帮助请寄给我akhilavishnu2@gmail.com。 请把这些代码行放在你的应用程序中,它很好的编码。

 private void Form1_FormClosing(object sender, FormClosingEventArgs e) { if(MessageBox.Show("Are you sure that you want to exit", MessageBoxButtons.YesNo, MessageBoxIcon.question) == DialogResult.No) { e.Cancel=true; } } //in formclose event private void Form1_FormClosed(object sender,FormClosedEventArgs e) { Application.Exit(); } 

如果你只是把下面的代码放到你的退出按钮的click事件中,它可以正常工作:)

 DialogResult quit = MessageBox.Show("Are you sure you want to quit?", "Quit", MessageBoxButtons.YesNo, MessageBoxIcon.Question) if (quit == DialogResult.Yes) this.Close();