Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles / desktop / WTL

Vista Goodies in C++: Monitoring the Computer's Power Status

5.00/5 (18 votes)
29 Dec 20067 min read 1   2.5K  
How to use power status notifications to make your applications conserve power when necessary.

Contents

Introduction

In this Vista Goodies article, I'll demonstrate how to monitor the computer's power status using new notifications that were added to Vista. For apps that may be CPU- or graphics-intensive — such as audio encoders, games, and media players — the ability to monitor the power status lets them be intelligent about power consumption when running on laptops. For example, a media player might automatically stop playing when the battery level falls below 15%, so the user will have plenty of time to attach a power cord, and won't have to scramble to close or stop the player to preserve what little power is left.

This article is written for the RTM version of Vista, using Visual Studio 2005, WTL 7.5, and the Windows SDK. See the introduction in the first Vista Goodies article for more information on where you can download those components.

This article's sample project is a dialog-based app that shows some simple animation. It monitors the computer's power status, updates the display to reflect the current status, and turns off the animation in situations where power conservation is important. For example, here is the dialog showing that the computer is running on AC power:

The "Hello, Bob!" text changes color every second in this case, since the computer isn't in a low-power situation and it's OK to use animation.

Power Schemes and Power Sources in Vista

Vista defines three default power schemes, named Power saver, Balanced, and High performance. Each scheme is a pre-set group of settings that control things like hard disk spin-down time, the maximum CPU speed to use, and so on. You can choose a power scheme using the battery tray icon or the Power Options control panel applet. Here is the tray selector with the Power saver scheme selected:

Vista also has some settings that can be different when the computer is using different power sources: batteries versus AC power. You can, for example, set the monitor to turn off after 3 minutes on batteries, or 15 minutes on AC power. Vista also monitors the battery power remaining, which is expressed as a percentage from 1 to 100.

Registering for Power Notifications

Apps can register to be notified of changes to the power scheme, power source, or battery power. The two APIs involved are RegisterPowerSettingNotification() and UnregisterPowerSettingNotification(). The prototype for RegisterPowerSettingNotification() is:

HPOWERNOTIFY RegisterPowerSettingNotification(
    HANDLE hRecipient, LPCGUID PowerSettingGuid, DWORD Flags);

hRecipient is a handle to the object that wants to receive notifications; in our case it's our dialog's HWND. PowerSettingGuid is a GUID that indicates which event we want to be notified of. Flags indicates what type of handle hRecipient is; in this sample code, the handle will always be an HWND, so we'll pass DEVICE_NOTIFY_WINDOW_HANDLE for Flags.

The relevant GUIDs for PowerSettingGuid are:

  • GUID_POWERSCHEME_PERSONALITY: register for changes in the power scheme
  • GUID_ACDC_POWER_SOURCE: register for changes in the power source
  • GUID_BATTERY_PERCENTAGE_REMAINING: register for changes in the battery power

RegisterPowerSettingNotification() returns an HPOWERNOTIFY, or NULL if an invalid parameter was passed. The HPOWERNOTIFY is only used when unregistering; the actual notifications occur through window messages.

How the Sample App Registers

CMainDlg has three HPOWERNOTIFY members:

HPOWERNOTIFY m_hPowerSchemeNotify, m_hPowerSourceNotify,
             m_hBatteryPowerNotify;

OnInitDialog() calls RegisterPowerSettingNotification() once for each type of notification. For example, this code registers for notifications about power scheme changes:

m_hPowerSchemeNotify = RegisterPowerSettingNotification (
                         m_hWnd, &GUID_POWERSCHEME_PERSONALITY,
                         DEVICE_NOTIFY_WINDOW_HANDLE );

if ( NULL == m_hPowerSchemeNotify )
  ATLTRACE("Failed to register for notification of power scheme changes!\n");

If RegisterPowerSettingNotification() fails, it's not a critical error; the app just won't be notified about that particular event.

Handling Power Notifications

When an app needs to be notified of a power change, the system sends it a WM_POWERBROADCAST message. WM_POWERBROADCAST is not a new message, but in Vista there is a new event code PBT_POWERSETTINGCHANGE and an associated data structure POWERBROADCAST_SETTING. When a PBT_POWERSETTINGCHANGE notification is sent, the message's lParam points to a POWERBROADCAST_SETTING struct, which looks like this:

typedef struct {
  GUID PowerSetting;
  DWORD DataLength;
  UCHAR Data[1];
} POWERBROADCAST_SETTING;

PowerSetting is a GUID that indicates what type of event occurred. The possible values for this member are the same GUIDs that are passed to RegisterPowerSettingNotification(). The rest of the struct is a variable-length chunk of data that contains the details of the event. This data varies among the different events:

PowerSetting value

Data description

GUID_POWERSCHEME_PERSONALITY

A GUID that indicates the active power scheme:

  • GUID_MAX_POWER_SAVINGS: the Power saver scheme
  • GUID_MIN_POWER_SAVINGS: the High performance scheme
  • GUID_TYPICAL_POWER_SAVINGS: the Balanced scheme

GUID_ACDC_POWER_SOURCE

An int that indicates the power source: 0 for AC power, 1 for batteries, or 2 for short-term batteries (for example, batteries in a UPS).

GUID_BATTERY_PERCENTAGE_REMAINING

An int that indicates the battery power remaining: 1 to 100.

How the Sample App Handles Notifications

CMainDlg has a few members that keep track of the current power situation:

enum EPowerScheme { pwrPowerSaver, pwrMaxPerf, pwrBalanced };

EPowerScheme m_eCurrPowerScheme;
bool m_bOnBattery;
int  m_nBatteryPower;
bool m_bUseAnimation;

These members are set to reasonable defaults (balanced scheme, not on batteries, animation on) and are changed in the WM_POWERBROADCAST handler. OnPowerBroadcast() starts by checking the event type, and returning if it's not PBT_POWERSETTINGCHANGE:

LRESULT CMainDlg::OnPowerBroadcast ( DWORD dwEvent, DWORD dwData )
{
  // We only care about Vista power setting notifications.
  if ( PBT_POWERSETTINGCHANGE != dwEvent )
    {
    SetMsgHandled(false);
    return 0;
    }

Next, we get a pointer to the POWERBROADCAST_SETTING struct sent with the message, and look at its PowerSetting member to see what event this notification is for. If it's GUID_POWERSCHEME_PERSONALITY, we determine what the new scheme is. If the scheme isn't one of the three predefined GUIDs, then we'll assume the scheme is Balanced.

POWERBROADCAST_SETTING* pps = (POWERBROADCAST_SETTING*) dwData;
 
  if ( sizeof(GUID) == pps->DataLength &&
       pps->PowerSetting == GUID_POWERSCHEME_PERSONALITY )
    {
    // This is a power scheme change notification
    GUID newScheme = *(GUID*)(DWORD_PTR) pps->Data;
 
    if ( GUID_MAX_POWER_SAVINGS == newScheme )
      {
      // New scheme: max power savings
      m_eCurrPowerScheme = pwrPowerSaver;
      m_cPowerScheme.SetWindowText ( _T("Power saver") );
      }
    else if ( GUID_MIN_POWER_SAVINGS == newScheme )
      {
      // New scheme: min power savings (max perf)
      m_eCurrPowerScheme = pwrMaxPerf;
      m_cPowerScheme.SetWindowText ( _T("Max performance") );
      }
    else if ( GUID_TYPICAL_POWER_SAVINGS == newScheme )
      {
      // New scheme: balanced
      m_eCurrPowerScheme = pwrBalanced;
      m_cPowerScheme.SetWindowText ( _T("Balanced") );
      }
    else
      {
      // Unrecognized scheme, we'll treat this like balanced
      m_eCurrPowerScheme = pwrBalanced;
      m_cPowerScheme.SetWindowText ( _T("Balanced") );
      }
    }

For power source notifications, we determine whether the new source is batteries or AC power:

else if ( sizeof(int) == pps->DataLength &&
          pps->PowerSetting == GUID_ACDC_POWER_SOURCE )
  {
  // This is a power source change notification
  int nPowerSrc = *(int*)(DWORD_PTR) pps->Data;

  m_bOnBattery = (0 != nPowerSrc);
  m_cPowerSource.SetWindowText ( m_bOnBattery ? _T("Battery") :
                                                _T("AC power") );
  }

Finally, for battery power notifications, we save the new percentage:

else if ( sizeof(int) == pps->DataLength &&
          pps->PowerSetting == GUID_BATTERY_PERCENTAGE_REMAINING )
  {
  // This is a battery power notification
  int nPercentLeft = *(int*)(DWORD_PTR) pps->Data;
  CString sPercentLeft;

  sPercentLeft.Format ( _T("%d"), nPercentLeft );
  m_cBatteryPower.SetWindowText ( sPercentLeft );
  m_nBatteryPower = nPercentLeft;
  }

Now that we've updated the static text controls to reflect the new power state, we determine whether to turn the animation on or off. The app's logic is this:

  1. Turn animation on if:
    • The current scheme is High performance, or
    • The current scheme is Balanced and the computer is not on batteries.
  2. Turn animation off if:
    • The current scheme is Balanced and the computer is on batteries, or
    • The current scheme is Power saver, or
    • The computer is on batteries and the battery power is 20% or less (no matter what the current scheme is).

bool bUseAnimation =
         (pwrMaxPerf == m_eCurrPowerScheme) ||
         (pwrBalanced == m_eCurrPowerScheme && !m_bOnBattery);
 
  if ( m_bOnBattery && m_cBatteryPower <= 20 )
    bUseAnimation = false;
 
  // If the animation setting has changed, save the new setting
  // and redraw the message area.
  if ( bUseAnimation != m_bUseAnimation )
    {
    m_bUseAnimation = bUseAnimation;
    m_cMessage.RedrawWindow();
    }
 
  return TRUE;    // allow all power actions
}

The m_bAnimation flag is then used elsewhere to determine how to draw the "Hello, Bob!" message. Here's how the dialog looks with animation on and off, respectively:

Conclusion

For CPU-intensive apps, being aware of the computer's power status can be really nice for your users. For example, a CD burning app could warn the user if the battery is too low, or a download manager could stop downloading in low-power situations to prevent the wireless network card from using up power. Little touches like that can give your apps a nice edge over others when running on Vista.

References

Copyright and License

This article is copyrighted material, ©2006 by Michael Dunn. I realize this isn't going to stop people from copying it all around the 'net, but I have to say it anyway. If you are interested in doing a translation of this article, please email me to let me know. I don't foresee denying anyone permission to do a translation, I would just like to be aware of the translation so I can post a link to it here.

The demo code that accompanies this article is released to the public domain. I release it this way so that the code can benefit everyone. (I don't make the article itself public domain because having the article available only on CodeProject helps both my own visibility and the CodeProject site.) If you use the demo code in your own application, an email letting me know would be appreciated (just to satisfy my curiosity about whether folks are benefiting from my code) but is not required. Attribution in your own source code is also appreciated but not required.

Revision History

  • October 5, 2006: Article first published.
  • December 26, 2006: Code tested on the RTM Vista build, intro updated accordingly.

Series navigation: « Using Glass in your UI | Using the New Vista File Dialogs »

License

This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here