Reputation: 73
I have a program that reads battery status in Windows that looks like this (simplified code):
#include <iostream>
#include <windows.h>
using namespace std;
int main(int argc, char *argv[]) {
SYSTEM_POWER_STATUS spsPwr;
if( GetSystemPowerStatus(&spsPwr) ) {
cout << "\nAC Status : " << static_cast<double>(spsPwr.ACLineStatus)
<< "\nBattery Status : " << static_cast<double>(spsPwr.BatteryFlag)
<< "\nBattery Life % : " << static_cast<double>(spsPwr.BatteryLifePercent)
<< endl;
return 0;
} else return 1;
}
spsPwr.BatteryLifePercent
holds remaining battery charge in percent and is of type BYTE
, which means it can only show reading in round numbers (i.e. int
). I notice that an application called BatteryBar can show battery percentage in floating point value.
BatteryBar is a .NET application. How can I get battery percentage reading in float/double using pure C/C++ with Windows API? (Solution that can be compiled with MinGW is preferable)
Upvotes: 7
Views: 11725
Reputation: 40736
The tool states that it does "Statistical Time Prediction" so I doubt it uses the direct value of SYSTEM_POWER_STATUS
.
Personally, I hardly can imagine what a floating-point precision would be good for, but anyway you could use ILSpy to see how they are doing it, or maybe you also could ask them how they do.
Upvotes: 0
Reputation: 136421
You can get this information using the WMI . try using the BatteryFullChargedCapacity
and BatteryStatus
classes both are part of the root\WMI
namespace.
To get the remaining battery charge in percent just must use the RemainingCapacity
(BatteryStatus) and FullChargedCapacity
(BatteryFullChargedCapacity) properties.
The remaining battery charge in percent is
(RemainingCapacity * 100) / FullChargedCapacity
for example if the FullChargedCapacity property report a 5266
value and the RemainingCapacity reports a 5039
, the reuslt will be 95,68932776 %
If you don't know how access the WMI from C++ read these articles
Upvotes: 4
Reputation: 109159
The .NET version doesn't actually provide you any more precision. It simply divides the BatterLifePercent
byte value by 100.0 and returns the result. Here are the contents of the getter in .NET.
public float BatteryLifePercent
{
get
{
this.UpdateSystemPowerStatus();
float num = ((float) this.systemPowerStatus.BatteryLifePercent) / 100f;
if (num <= 1f)
{
return num;
}
return 1f;
}
}
UpdateSystemPowerStatus()
calls WINAPI's GetSystemPowerStatus()
, which in turn updates systemPowerStatus
.
Upvotes: -1
Reputation: 385204
Well, as you said, the Windows API provides only an integral percentage value. And, as you implied, .NET provides a floating-point one.
That means that, to use the floating-point one, you have to use .NET. That said, the .NET value is between 0.0
and 1.0
, and it's not clear from the documentation whether you actually gain more precision.
Upvotes: 1