Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C get battery life under Windows 7

I'm trying to code a program that gets the % of a laptop battery and then displays a CMD showing a message (for example: 10% -> "Low battery!"). I've tried to google it, and it seems they all tried with C++ or C#. Can anybody help me with C, please?

Edit: thanks zakinster for your reply. Shouldn't it look something like this? This code ain't working.

#include <Windows.h>
#include <Winbase.h>
#include <stdio.h>
#include <string.h>
#include <stdlib.h>

int main() {
    SYSTEM_POWER_STATUS status;
    GetSystemPowerStatus(&status);
    unsigned char battery = status.BatteryLifePercent;
    printf("%s", battery);
}
like image 685
user3439355 Avatar asked Mar 19 '14 19:03

user3439355


1 Answers

GetSystemPowerStatus from the Win32 API should provide the information you need :

SYSTEM_POWER_STATUS status;
if(GetSystemPowerStatus(&status)) {
    unsigned char battery = status.BatteryLifePercent;
    /* battery := 0..100 or 255 if unknown */
    if(battery == 255) {
        printf("Battery level unknown !");
    }
    else {
        printf("Battery level : %u%%.", battery);
    }
} 
else {
    printf("Cannot get the power status, error %lu", GetLastError()); 
}

See the documentation of the SYSTEM_POWER_STATUS structure for a complete list of contained information.

like image 147
zakinster Avatar answered Sep 27 '22 01:09

zakinster