Den is a DZone Zone Leader and has posted 460 posts at DZone. You can read more from them at their website. View Full User Profile

PowerManager class in Windows API Code Pack

04.14.2010
| 5065 views |
  • submit to reddit

The PowerManager class is the key element of the Windows API Code Pack when it comes to power management API. It provides an interface to the computer power management system, providing information about its current status and capabilities. Its structure is fairly simple organization-wise, at the same time being a wrapper for a lot of native API calls. It exposes a series of properties and functions (there are also several event handlers present to track changing power states). The properties are outlined below:
 


The developer can easily check these properties to trigger specific application events. All properties are read-only. If the developer wants to check the state of the power source, there is a separate function that gives the possibility to check battery life. Here is a code snippet that shows how a battery time can be checked:

 

void CheckBatteryLife(int MaxMinutes, string Notification)
{
int minutes = (int)PowerManager.GetCurrentBatteryState().EstimatedTimeRemaining.TotalMinutes;

if (minutes <= MaxMinutes)
{
MessageBox.Show(Notification);
}
}


The function presented above checks the remaining time of activity for the current battery (in minutes – the measurement type can be changed) and notifies the user if the value of pre-set maximum minutes is equal or bigger than the curent value returned by the API.


As you see, there is the GetBatteryState function I did not mention before. Its structure is outlined below.
 


This function only applies to machine that have a battery (mostly laptops), therefore before using it a good idea would be to check the PowerSource property. The properties it returns are read-only.


Notice the fact, that EstimatedTimeRemaining is in fact an instance of the TimeSpan class, therefore you can assign it to an instance of TimeSpan and perform time addition/subtraction operations with it.

TimeSpan span = PowerManager.GetCurrentBatteryState().EstimatedTimeRemaining;