在用户选择退出 WinForms 程序后,有没有比这更好的方法来处理做某事的任务:
[编辑 1:回应 'NoBugz 的评论]在这种情况下,表单上没有 ControlBox,并且有理由在用户选择关闭表单时发生的事情中设置一层间接性 [/edit 1]
[编辑 2:响应格林威治标准时间 +7 18:35 1 月 20 日的所有评论]也许使用淡出 MainForm 是一个简单的说明,说明您在关闭应用程序时可能想要做什么:用户无法与之交互:不言而喻,这与用户终止应用程序的决定有关。[/编辑 2]
(使用某种形式的线程?)(对多线程应用程序的影响?)(这段代码“难闻”吗?)
// 'shutDown is an external form-scoped boolean variable
//
private void Form1_FormClosing(object sender, FormClosingEventArgs e)
{
// make sure we don't block Windows ShutDown
// or other valid reasons to close the Form
if (e.CloseReason != CloseReason.ApplicationExitCall) return;
// test for 'shutDown flag set here
if (shutDown) return;
// cancel closing the Form this time through
e.Cancel = true;
// user choice : default = 'Cancel
if (MessageBox.Show("Exit Application ?", "", MessageBoxButtons.OKCancel, MessageBoxIcon.Question, MessageBoxDefaultButton.Button2) == System.Windows.Forms.DialogResult.OK)
{
// user says Exit : activate Timer, set the flag to detect Exit
timer1.Enabled = true;
shutDown = true;
}
}
摘要:在一个非常标准的 WinForms 应用程序中(一个 MainForm 在 Program.cs 中以标准方式启动):在 MainForm 的 FormClosing 事件处理程序中:
立即退出(触发默认行为:关闭 MainForm 并退出应用程序)如果:
一种。CloseReason 是任何其他 CloseReason.ApplicationExitCall
湾。如果一个特殊的布尔变量设置为 true,或者
如果没有立即退出:取消对 FormClosing 的“第一次调用”。
然后用户通过 MessageBox.Show 对话框选择退出应用程序或取消:
一种。如果用户取消,当然,应用程序保持“原样”。
湾。如果用户选择“退出”:
将特殊的布尔标志变量设置为 true
运行一个 Timer 来做一些特殊的事情。
当 Timer 代码中的内部测试检测到“特殊内容”已完成时,它会调用 Application.Exit