如何在WinForms应用程序中检测Windows关机
本文关键字:检测 Windows 关机 应用程序 WinForms | 更新日期: 2023-09-27 18:18:03
我试图在WinForms (c#)中创建一个应用程序,该应用程序将在我的系统中连续运行,并能够检测windows关机/重新启动/注销,并创建一个快捷键(例如esc),它将在我想要的时候自动取消关机。但是,首先我需要学习如何使用c# Windows窗体应用程序检测Windows何时关闭。
看一下MSDN的例子:
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_Closing(
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;
}
}
}