Sunday, May 08, 2011

Responding to Windows power management events (standby, hibernate, shutdown)

Introduction
This article provides a way for a .NET Windows application to respond to Windows Power Management events such as suspend, hibernate, standby, power switch etc.

Background
My organization uses Lotus Notes as an email client which hangs badly on our laptops when we go from one meeting room to another since the network breaks between the meeting rooms. And since Lotus Notes continuously monitors the network for any incoming mail, it tends to get hung up taking the whole window down with it. So to avoid forcefully restarting Windows, I created this application to capture the standby event and close the mail client before going to standby and automatically start the mail client when the system resumes. I got a lot of reference help from the article: http://www.codeproject.com/KB/system/OSEvents.aspx.

Using the code
We need to override the WndProc method which will allow us to interact with all the events that the OS tends to provide to the application on different conditions.
The Windows OS communicates with the application by sending different messages which need to be captured and worked on. For this implementation, we need to capture the WM_POWERBROADCAST (0x0218) value which will specify that this is a power event change and that we need to capture the WParam which can have the following values:

PBT_APMQUERYSUSPEND (0x0000)
PBT_APMRESUMESUSPEND (0x0007)
PBT_APMQUERYSTANDBY (0x0001)
PBT_APMQUERYSUSPENDFAILED (0x0002)
PBT_APMQUERYSTANDBYFAILED (0x0003)
PBT_APMSUSPEND (0x0004)
PBT_APMSTANDBY (0x0005)
PBT_APMRESUMECRITICAL (0x0006)
PBT_APMRESUMESTANDBY (0x0008)
PBTF_APMRESUMEFROMFAILURE (0x00000001)
PBT_APMBATTERYLOW (0x0009)
PBT_APMPOWERSTATUSCHANGE (0x000A)
PBT_APMOEMEVENT (0x000B)
PBT_APMRESUMEAUTOMATIC (0x0012)

Read more: Codeproject