5

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);
}
Benjamin Barenblat
  • 1,311
  • 6
  • 19
  • You shouldn't need to include `winbase.h`, it's included by `windows.h`. See my last edit for a correct error checking. Also `status.BatteryLifePercent` is a 8bit unsigned integer representing the battery level percent (from 0 to 100) or 255 if unknown, it shouldn't be printed as a string character. – zakinster Mar 19 '14 at 20:30
  • Thanks a lot, it's working! I'll add some tweaks now ;) – user3439355 Mar 19 '14 at 21:02
  • I get docs in C++ and C# all the time but not C and can't understand them it's so annoying. I don't think you need all those header files either `stdio.h` and `windows.h` will do :) – Xantium Sep 20 '17 at 23:43

1 Answers1

6

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.

zakinster
  • 10,508
  • 1
  • 41
  • 52