I need to stop our Windows service when a PC is powered down into Suspend mode and restart it when the PC is resumed again. What is the proper way to do this?
You should 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 the power statuses.
Also, you'll need to set the ServiceBase.CanHandlePowerEvent Property to true
.
protected override void OnStart(string[] args)
{
this.CanHandlePowerEvent = true;
}
Comment on Alex Filipovici Answer edited May 16 '13 at 17:05:
CanHandlePowerEvent = true;
must be set in the constructor
Setting it in OnStart()
is too late and causes 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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With