我的电脑有一个备用电源,它与电脑和墙壁串联连接。当我从墙上拔下电源线时,备用电源会在 2-5 分钟后关闭计算机。正是在这段时间里,我想使用以下代码将数据写入文件:
private void Form1_FormClosing(object sender, FormClosingEventArgs e)
{
if (e.CloseReason.Equals(CloseReason.WindowsShutDown))
{
writeContents("Interrupted");
sendMessage("PWR - The Spring Test Machine has stopped");
return;
}
if (e.CloseReason.Equals(CloseReason.UserClosing))
{
if (MessageBox.Show("You are closing this application.\n\nAre you sure you wish to exit ?", "Warning: Not Submitted", MessageBoxButtons.YesNoCancel, MessageBoxIcon.Stop) == DialogResult.Yes)
{
writeContents("Interrupted");
return;
}
else
e.Cancel = true;
}
}
问题是它不起作用。我认为闭幕式从未被召集过。任何想法将不胜感激。谢谢。
请您参考如下方法:
when you use taskmanager to "kill" the appliction, it doesn't fire any events, It simply stops the execution, This is how you close an application that has frozen. if you waited for it to handle any events, then it would still be frozen.
as for when you restart the computer or shutdown, the event will be called only if there is enough time, they system tells all applications it is shutting down and only gives them a short amount of time to handle business before it kills them. Windows 7 will show a dialog telling you which applications are still busy and ask you if you want to kill them and shutdown, or cancel. But as for XP, it just kills them after X amount of seconds.
这几乎就是我对 FormClosing 行为的想象……Application.ApplicationExit Event 会是一个更好的监听事件吗?
