5

In a Windows Service, I need to detect when the computer goes into sleep and when it wakes up, and run some code on these events. This needs to be done for sleep, standby and hibernate power modes.

How do I do that ?

driis
  • 161,458
  • 45
  • 265
  • 341

2 Answers2

9

Override the ServiceBase.OnPowerEvent() method.

Hans Passant
  • 922,412
  • 146
  • 1,693
  • 2,536
  • 3
    Don't forget to set the ServiceBase.CanHandlePowerEvent = true; otherwise, you won't get any OnPowerEvents. – Omri Gazitt Oct 27 '13 at 02:17
  • on my project the method OnPowerEvent is never triggered even though CanHandlePowerEvent is set to true. Any idea on what might be happening? – YaKs Mar 18 '20 at 15:45
1

I'm not sure because I have never did it myself but recently I came accross OnSessionChange method. I can't promise it allows to catch sleep event, but may be studying it's documentation in MSDN or elswere can help you.

http://msdn.microsoft.com/en-us/library/system.serviceprocess.servicebase.canhandlesessionchangeevent.aspx

Sergej Andrejev
  • 9,091
  • 11
  • 71
  • 108