2013-04-09 26 views

回答

3
private static string GetBatteryLevel() 
{ 
    ObjectQuery query = new ObjectQuery("SELECT * FROM Win32_Battery"); 
    using (ManagementObjectSearcher searcher = new ManagementObjectSearcher(query)) 
    { 
     using (ManagementObjectCollection results = searcher.Get()) 
     { 
      using (var enumerator = results.GetEnumerator()) 
      { 
       if (!enumerator.MoveNext()) 
        return string.Empty; 

       return string.Format("{1} {0}%", enumerator.Current["EstimatedChargeRemaining"], 
            enumerator.Current["BatteryStatus"].ToString() == "1" 
             ? string.Empty 
             : "Charging:"); 
      } 
     } 
    } 
} 

您可以使用Windows Management Instrumentation

+0

我試圖創建使用Windows窗體應用程序相同。但是,當我嘗試使用'System.Data.Objects'命名空間時,我的Visual Studio顯示錯誤。您在Visual Studio中選擇了哪個項目模板? – TheRookierLearner 2013-04-09 14:41:14

+0

@TheRookierLearner只要您引用'System.Management'程序集,您就可以使用任何您喜歡的項目模板。 從解決方案資源管理器右鍵單擊您的項目,然後單擊「添加引用」,然後搜索「System.Management」(http://i.imgur.com/CD43hdi.png)。 一旦你添加了你的引用,在類'using System.Management;' – 2013-04-09 15:27:06

+0

上添加一個using指令這不會發生在我的案例中([link](http://i.imgur.com/LlKz8Rf.jpg) ))。 – TheRookierLearner 2013-04-09 16:49:46

相關問題