【发布时间】:2010-01-19 19:17:02
【问题描述】:
在用户选择退出 WinForms 程序后,有没有更好的方法来处理做某事的任务:
[edit 1 : 回应 'NoBugz 的评论] 在这种情况下,表单上没有 ControlBox,并且有理由放置一层当用户选择关闭表单时发生的事情的间接性[/edit 1]
[edit 2 : 响应所有 cmets 截至 GMT +7 18:35 January 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
b.如果一个特殊的布尔变量设置为 true,或者
如果没有立即退出:取消对 FormClosing 的“第一次调用”。
-
然后用户通过 MessageBox.Show 对话框做出选择,退出应用程序或取消:
一个。如果用户取消,当然,应用程序保持“原样”。
b.如果用户选择了“退出:
将特殊的布尔标志变量设置为真
运行一个 Timer 来做一些特殊的事情。
当 Timer 代码中的内部测试检测到“特殊内容”已完成时,它会调用 Application.Exit
【问题讨论】:
-
@nobugz 感谢您的评论;在这种情况下,我省略了说Form上没有ControlBox。我将在其中进行编辑。
-
@nobugz 感谢您的 cmets !这是根据客户的要求设计的,有点不标准的 WinForms UI;在关闭应用程序时通过计时器的“滴答”事件执行某些代码是有原因的:在视觉上,事情确实发生了,但是当应用程序被关闭时,最终用户无法与之交互。为了关闭应用程序而添加一个必需的验证步骤是“规范”的一部分。
标签: c# winforms formclosing