2011-11-21 210 views
1

我試圖讓充電%,而正是那就是視窗顯示相同的文本 - 不充電,充滿電,充電如何使用WMI從WPF應用程序獲取電池充電狀態?

我使用WMI查詢。

我不想對文本進行硬編碼,因爲它每次工作都不一樣。有時顯示95% - 不收費,或可以收費。

有什麼方法可以得到結果文本嗎?

我可以做什麼,只是爲了檢查它是否是100%的收費,顯示全部收費。

但對於96%,它的工作方式不同,有時Windows顯示充電,或不在充電

回答

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

我知道這是一個老問題,但另一種方式來獲取有關電池的信息而不是使用查詢是使用ManagementClass。這裏有一些代碼來獲得電池狀態(FullyCharged,Discharge等等)和一些代碼來獲得估計的剩餘電池百分比。

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; 
    }