Reputation: 2412
I'm trying to get charging percent, and exactly the same text that is Windows showing - Not Charging, Full Charged, Charging
I'm using wmi-query.
I don't want to hard-code that texts, because it's working differently every time. Sometimes it's showing 95 percent- Not Charging, or can be Charging.
Is there any way to get that result text?
What I can do, just to check if it is 100 percent charged, to display Full Charged.
But for 96 percent, it is working differently, sometimes Windows display Charged, or Not Charging
Upvotes: 1
Views: 3763
Reputation: 2368
I know this is an old question, but another way to get the information about the battery instead of using the query is to use the ManagementClass. Here's some code to get the battery status (FullyCharged, Discharging, etc...) and some code to get the estimated remaining battery percentage.
public enum BatteryStatus : ushort
{
Discharging = 1,
AcConnected,
FullyCharged,
Low,
Critical,
Charging,
ChargingAndHigh,
ChargingAndLow,
ChargingAndCritical,
Undefined,
PartiallyCharged
}
...
/// <summary>
/// Gets the battery status.
/// </summary>
/// <returns></returns>
public static BatteryStatus GetBatteryStatus()
{
ManagementClass wmi = new ManagementClass("Win32_Battery");
ManagementObjectCollection allBatteries = wmi.GetInstances();
BatteryStatus status = BatteryStatus.Undefined;
foreach (var battery in allBatteries)
{
PropertyData pData = battery.Properties["BatteryStatus"];
if (pData != null && pData.Value != null && Enum.IsDefined(typeof(BatteryStatus), pData.Value))
{
status = (BatteryStatus)pData.Value;
}
}
return status;
}
You can use the following to get the remaining percent.
/// <summary>
/// Gets the percent of power remaining in the battery.
/// </summary>
/// <returns></returns>
public static double GetBatteryPercent()
{
ManagementClass wmi = new ManagementClass("Win32_Battery");
ManagementObjectCollection allBatteries = wmi.GetInstances();
double batteryLevel = 0;
foreach (var battery in allBatteries)
{
batteryLevel = Convert.ToDouble(battery["EstimatedChargeRemaining"]);
}
return batteryLevel;
}
Upvotes: 2
Reputation: 17850
Use the Win32_Battery class:
static string GetBatteryStatus() {
ManagementScope scope = new ManagementScope("//./root/cimv2");
SelectQuery query = new SelectQuery("Select BatteryStatus From Win32_Battery");
using(ManagementObjectSearcher searcher = new ManagementObjectSearcher(scope, query)) {
using(ManagementObjectCollection objectCollection = searcher.Get()) {
foreach(ManagementObject mObj in objectCollection) {
PropertyData pData = mObj.Properties["BatteryStatus"];
switch((Int16)pData.Value) {
//...
case 2:return "Not Charging";
case 3:return "Fully Charged";
case 4:return "Low";
case 5: return "Critical";
//...
}
}
}
}
return string.Empty;
}
Upvotes: 1