在窗口服务中检测关闭

我有一个Windows服务,可以获取用户详细信息并将结果保存到日志文本文件中。 而且,我的问题是当我关闭或注销我的系统时,我也想将我的系统中的时间保存到该日志文件中。 但是,我不知道该怎么做。

我检查了winproc方法以检测关机操作,但我无法在窗口服务上使用它,谷歌搜索发现它只能用于表单。 我们如何检测用户是否已点击关机或注销并执行某些操作。 所以,请给我一些想法或建议。

我已经使用它进行注销,但是在我注销系统时进行日志输入

protected override void OnSessionChange(SessionChangeDescription changeDescription) { this.RequestAdditionalTime(250000); //gives a 25 second delay on Logoff if (changeDescription.Reason == SessionChangeReason.SessionLogoff) { // Add your save code here StreamWriter str = new StreamWriter("D:\\Log.txt", true); str.WriteLine("Service stoped due to " + changeDescription.Reason.ToString() + "on" + DateTime.Now.ToString()); str.Close(); } base.OnSessionChange(changeDescription); } 

要关闭,请覆盖OnShutdown方法:

 protected override void OnShutdown() { //your code here base.OnShutdown(); } 

注销:

首先,在Service Constructor中向Microsoft.Win32.SystemEvents.SessionEnded添加一个事件处理程序:

 public MyService() { InitializeComponent; Microsoft.Win32.SystemEvents.SessionEnded += new Microsoft.Win32.SessionEndedEventHandler(SystemEvents_SessionEnded); } 

然后添加处理程序:

 void SystemEvents_SessionEnded(object sender, Microsoft.Win32.SessionEndedEventArgs e) { //your code here } 

这应该捕获任何结束的会话,包括控制台本身(运行服务的那个)。

我知道我是从死里复活的,但我发现它很有帮助,并希望在这个主题上添加一些内容。 我正在实现一个托管在Windows服务中的WCF双工库并遇到了这个线程,因为我需要在Windows服务中检测用户何时注销或关闭计算机。 我在Windows 7和Windows 10上使用.Net Framework 4.6.1。就像之前建议的关闭对我ServiceBase.OnShutdown()是覆盖ServiceBase.OnShutdown()如下所示:

 protected override void OnShutdown() { //Your code here //Don't forget to call ServiceBase OnShutdown() base.OnShutdown(); } 

请记住将以下内容添加到服务的构造函数中以允许捕获关闭事件:

 CanShutdown = true; 

然后捕获用户注销时,锁定屏幕,切换用户等等,你可以像这样覆盖OnSessionChange方法:

 protected override void OnSessionChange(SessionChangeDescription changeDescription) { if (changeDescription.Reason == SessionChangeReason.SessionLogoff) { //Your code here... //I called a static method in my WCF inbound interface class to do stuff... } //Don't forget to call ServiceBase OnSessionChange() base.OnSessionChange(changeDescription); } 

当然记得将以下内容添加到服务的构造函数中以允许捕获会话更改事件:

 CanHandleSessionChangeEvent = true; 

您应该在服务中覆盖OnShutdown

 // When system shuts down protected override void OnShutdown() { // Add your save code here base.OnShutdown(); } 

您可能还想覆盖OnStop

 // When the user presses stops your service from the control panel protected override void OnStop() { // Add your save code here too base.OnStop(); } 

编辑:
如果你真的想要监听关闭事件,那么Microsoft.Win32.SystemEvents.SessionEnding就是你的选择。

也许你可以用它 。 不时轮询有问题的方法(1秒间隔),你就能做你想做的事。

您需要RegisterServiceCtrlHandlerEx API调用。