How can I stop the shutdown and shut down Windows when the PC pauses / resumes?

I need to stop our Windows service when the computer is shut down in Suspend mode and restart it when the computer resumes again. What is the right way to do this?

+6
source share
4 answers

You must override the ServiceBase.OnPowerEvent method.

protected override bool OnPowerEvent(PowerBroadcastStatus powerStatus) { if (powerStatus.HasFlag(PowerBroadcastStatus.QuerySuspend)) { } if (powerStatus.HasFlag(PowerBroadcastStatus.ResumeSuspend)) { } return base.OnPowerEvent(powerStatus); } 

The PowerBroadcastStatus enumeration explains power states. In addition, you need to set the ServiceBase.CanHandlePowerEvent property to true .

 protected override void OnStart(string[] args) { this.CanHandlePowerEvent = true; } 
+6
source

Comments on Alex Filipovici Answer edited May 16 '13 at 17:05:

 CanHandlePowerEvent = true; 

must be installed in the constructor

Installation in OnStart() too late and raises this exception:

 Service cannot be started. System.InvalidOperationException: Cannot change CanStop, CanPauseAndContinue, CanShutdown, CanHandlePowerEvent, or CanHandleSessionChangeEvent property values after the service has been started. at System.ServiceProcess.ServiceBase.set_CanHandlePowerEvent(Boolean value) at foo.bar.OnStart(String[] args) at System.ServiceProcess.ServiceBase.ServiceQueuedMainCallback(Object state) 
+1
source

This is one of the features of the Windows service.

Shutdown

Shutdown occurs automatically when you turn off the PC. No need to do anything. To perform any cleanup, you need to override methods like ServiceBase , such as OnPowerEvent , a sample

 public class WinService : ServiceBase { protected override void OnStart(string[] args) { ... } protected override void OnStop() { ... } protected override bool OnPowerEvent(PowerBroadcastStatus powerStatus) { ... } } 

Start

To start the service automatically, you need to install it ServiceStartMode.Automatic , as here

 [RunInstaller(true)] public class WindowsServiceInstaller : Installer { private readonly ServiceProcessInstaller _process; private readonly ServiceInstaller _service; public WindowsServiceInstaller() { _process = new ServiceProcessInstaller { Account = ServiceAccount.LocalSystem }; _service = new ServiceInstaller { ServiceName = "FOO", StartType = ServiceStartMode.Automatic, // <<<HERE Description = "Foo service" }; Installers.Add(_process); Installers.Add(_service); } } 
0
source

Instead of stopping your service, you could just stop processing with something like ...

 Microsoft.Win32.SystemEvents.PowerModeChanged += this.SystemEvents_PowerModeChanged; private void SystemEvents_PowerModeChanged(object sender, Microsoft.Win32.PowerModeChangedEventArgs e) { if (e.Mode == PowerModes.Suspend) { } if (e.Mode == PowerModes.Resume) { } } 
0
source

Source: https://habr.com/ru/post/945183/


All Articles