这是我现在的代码:
private void Form1_FormClosing(object sender, FormClosingEventArgs e)
{
if (e.CloseReason == CloseReason.UserClosing)
{
if (MessageBox.Show("Are you Sure you want to Exit. Click Yes to Confirm and No to continue", "WinForm", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.No)
{
if (timer2.Enabled == true)
{
if (MessageBox.Show("Quit now will delete all the file of the current operation. Click Yes to Confirm and No to continue", "WinForm", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.No)
{
e.Cancel = true;
}
else
{
e.Cancel = false;
return;
}
}
e.Cancel = true;
}
else
{
e.Cancel = false;
}
}
}
我想要做的是如果未启用timer2,则退出请求用户退出或不定期。
但是如果timer2启用了,那么首先询问是否退出,然后询问第二个内部问题“现在退出将删除当前操作的所有文件” 如果用户在第二个问题上单击是,则执行某些操作(删除文件)并退出。 但是,如果用户在第二个问题上单击“否”,则不会使程序继续运行。
但是现在它现在不能正常工作如果我在第一个问题上单击否,那么如果启用了timer2,它将会询问secod问题。如果timer2为true,我在第一个问题上单击是,它将退出程序而不询问第二个问题。
一团糟。我希望启用timer2是真的问第二个问题: 在第二个问题用户做了删除文件做任何需要然后关闭一切。 在第二个问题上,用户没有返回并保持程序正常工作。
如果在第一个问题上启用了timer2,如果用户确实为YES则退出该程序,如果用户没有,则保持程序正常工作。
答案 0 :(得分:3)
如果计时器仍然启用,您只想询问用户第二个问题? 以下是
private void Form1_FormClosing(object sender, FormClosingEventArgs e)
{
if (e.CloseReason == CloseReason.UserClosing)
{
if (MessageBox.Show("Are you Sure you want to Exit. Click Yes to Confirm and No to continue", "WinForm", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
{
if (timer2.Enabled == true)
{
if (MessageBox.Show("Quit now will delete all the file of the current operation. Click Yes to Confirm and No to continue", "WinForm", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
{
//do your work here like delete files etc
}
else
{
e.Cancel = false;
return;
}
}
e.Cancel = true;
}
else
{
e.Cancel = false;
}
}
}
答案 1 :(得分:1)
您的代码可以通过两种方式简化:
e.Cancel = false
- 这是原始值,设置它没有意义。return
- 这可以减少复杂的嵌套。此外,我想您要检查DialogResult.Yes
的第一个MessageBox,而不是No
。
private void Form1_FormClosing(object sender, FormClosingEventArgs e)
{
if (e.CloseReason != CloseReason.UserClosing)
return; // Not closing - we don't care.
var res = (MessageBox.Show("Are you Sure you want to Exit? Click Yes to Confirm and No to continue",
"WinForm", MessageBoxButtons.YesNo, MessageBoxIcon.Question);
if (res != DialogResult.Yes) {
// User didn't say Yes - don't exit.
e.Cancel = true;
return;
}
if (timer2.Enabled == true)
{
// Only ask this question if timer2 is running.
res = MessageBox.Show("Quit now will delete all the file of the current operation. Click Yes to Confirm and No to continue",
"WinForm", MessageBoxButtons.YesNo, MessageBoxIcon.Question);
if (res != DialogResult.Yes) {
e.Cancel = true;
return; // User didn't say Yes - don't exit.
}
}
// Quit
}