我在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但没有任何事情发生。系统停机,没有等待。
答案 0 :(得分:0)
这就是我上一次想要阻止Windows关闭的方式:
Public Form1()
{
InitializeComponent();
SystemEvents.SessionEnding += SessionEndingEvtHandler;
}
private void SessionEndingEvtHandler(object sender, SessionEndingEventArgs e)
{
e.Cancel = true;
}