C#.net winforms应用程序Sessionending事件

当我关闭系统时, SystemEvents.SessionEnding事件没有被触发…

您是否尝试过将此事件作为微软的例子来实现? 像那样

重要说明:控制台应用程序不会引发SessionEnding事件。

仅在消息泵运行时才会引发此事件。 在Windows服务中,除非使用隐藏表单或手动启动消息泵,否则不会引发此事件。 有关演示如何使用Windows服务中的隐藏表单处理系统事件的代码示例,请参阅SystemEvents类。 – > .NET Windows服务中的消息泵

 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; } } } 

更多信息 ? 请参见此处: SystemEvents.SessionEnding事件

您可以尝试这一点 – 首先打开gpedit.msc,转到配置 – >管理模板 – >系统 – >关闭选项。 现在选择关闭阻止或取消关闭的应用程序的自动终止。

并阅读Microsoft SystemEvents.SessionEnding事件文档以进行进一步开发。