我正在尝试获取充值百分比,与Windows显示的文本完全相同 - 不充电,完全充电,充电
我正在使用wmi-query。
我不想硬编码那些文本,因为它每次都有不同的工作方式。 有时它显示95% - 不充电,或者可以充电。
有没有办法获得结果文本?
我可以做什么,只是为了检查它是否100%充电,以显示完全充电。
但对于96%,它的工作方式不同,有时Windows显示Charged,或Not Charging
答案 0 :(得分:2)
使用Win32_Battery类:
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;
}
答案 1 :(得分:2)
我知道这是一个老问题,但获取有关电池的信息而不是使用查询的另一种方法是使用ManagementClass。这里有一些代码可以获取电池状态(FullyCharged,Discharging等等)和一些代码来获得估计的剩余电量百分比。
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;
}
您可以使用以下内容获取剩余的百分比。
/// <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;
}