Windows API: Programmatically Get System Power/Battery Status

See related: Windows API examples & AC/DC Power in .NET

Ever need to know when a Windows laptop computer is on battery power, perhaps to halt a power hungry / cpu intensive routine? Just a few lines of code can determine if a Windows computer is plugged on AC or not plugged in on DC/battery power.

#include <windows.h>

SYSTEM_POWER_STATUS sps;

if(GetSystemPowerStatus(&sps))
{
	if(sps.ACLineStatus == 255)
	{
		// STATUS IS UNKNOWN
	}
	else
	{
		if(!sps.ACLineStatus)
		{
			// THEN ON BATTERY POWER; THIS IS PROBABLY THE MOST USEFUL MEMBER
		}
		else if(sps.ACLineStatus & 1)
		{
			// THEN PLUGGED IN
		}
	}

	if(sps.BatteryFlag == 255)
	{
		// STATUS IS UNKNOWN
	}
	else
	{
		if(sps.BatteryFlag & 1)
		{
			// THEN BATTERY AT 66% OR GREATER CAPACITY
		}
		if(sps.BatteryFlag & 2)
		{
			// THEN BATTERY AT 33% OR LESS CAPACITY
		}
		if(sps.BatteryFlag & 4)
		{
			// THEN BATTERY AT 5% OR LESS CAPACITY
		}
		if(sps.BatteryFlag & 8)
		{
			// THEN BATTERY IS CURRENTLY CHARGING
		}
		if(sps.BatteryFlag & 128)
		{
			// THEN NO BATTERY
		}
	}

	if(sps.BatteryLifePercent == 255)
	{
		// STATUS IS UNKNOWN
	}
	else
	{
		// BATTERY PERCENTAGE 0 to 100
		if(sps.BatteryLifePercent < 25)
		{
			// HALT CPU INTENSIVE OPERATIONS
		}
	}

	if(sps.SystemStatusFlag)
	{
		// "BATTERY SAVER" IS ON SO SAVE ENERGY WHERE POSSIBLE
	}
	else
	{
		// "BATTERY SAVER" IS OFF SO LET'R RIP!!
	}
}

Here are all the members of SYSTEM_POWER_STATUS:

typedef struct _SYSTEM_POWER_STATUS {
  BYTE  ACLineStatus;
  BYTE  BatteryFlag;
  BYTE  BatteryLifePercent;
  BYTE  SystemStatusFlag;
  DWORD BatteryLifeTime;
  DWORD BatteryFullLifeTime;
} SYSTEM_POWER_STATUS;

Cookies are simple text files stored on the user's computer. They are used for adding features and security to this site.
OK