【发布时间】:2016-04-28 23:25:02
【问题描述】:
我正在关注 MSDN 上的这些示例代码,以防止 Windows 7 在用户确认之前关闭:
private static int WM_QUERYENDSESSION = 0x11;
private static bool systemShutdown = false;
protected override void WndProc(ref System.Windows.Forms.Message m)
{
if (m.Msg == WM_QUERYENDSESSION)
{
MessageBox.Show("queryendsession: this is a logoff, shutdown, or reboot");
systemShutdown = true;
}
// If this is WM_QUERYENDSESSION, the closing event should be
// raised in the base WndProc.
base.WndProc(ref m);
} //WndProc
private void Form1_FormClosing(System.Object sender, System.ComponentModel.CancelEventArgs e)
{
if (systemShutdown)
// Reset the variable because the user might cancel the
// shutdown.
{
systemShutdown = false;
if (DialogResult.Yes == MessageBox.Show("My application",
"Do you want to save your work before logging off?",
MessageBoxButtons.YesNo))
{
e.Cancel = true;
}
else
{
e.Cancel = false;
}
}
}
但我面临的问题是在一台 PC 上,即使显示“queryendsession:这是注销、关闭或重新启动”(因此收到 WM_QUERYENDSESSION),Windows 7 也不会等待用户的确认并快速关闭。在其他 PC 上,这些代码运行良好。所以我想知道发生了什么。非常感谢。
顺便说一句:我尝试在 Form1_FormClosing 中直接发送 e.Cancel = false 但没有任何反应。系统关闭,无需等待。
【问题讨论】:
-
程序可以阻止关机的日子已经过去了。显示一个消息框是一个非常糟糕的主意,用户无法点击它。注意您的 FormClosing 事件处理程序中的 e.CloseReason 属性,如果机器正在关闭,那么您将不得不进行猜测。很少有用户喜欢丢掉工作。
-
谢谢提醒我查原因。原因是 systemshutdown,这对于所有测试的 PC 都是一样的。但是无论你用 e.Cancel 做什么,只有上面提到的那个会立即关闭。