Sometimes programs need to know the power status of a computer. In this application you can learn the status of the computer battery in a simple way.
Before start coding, we must know some words
System.Management Namespace : This namespace contains such as ManagementObjectSearcher, ManagementQuery, ManagementEventWatcher classes that can be used when creating a computer monitor application.
Add System.Management refernce to your project.
Then following code we can query all information about Laptop Battery through Win32_Battery class
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 | static void Main(string[] args) { /*Get Laptop Battery Status using C#*/ ManagementObjectSearcher mos = new ManagementObjectSearcher("select * from Win32_Battery"); foreach (ManagementObject mo in mos.Get()) { Console.WriteLine("Battery Name\t:{0}",mo["Name"]); Console.WriteLine("Charge \t\t:{0}%", mo["EstimatedChargeRemaining"]); } Console.ReadLine(); } |
If you want to get more information about battery, you can look the following code
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 | static void Main(string[] args) { /*Get Laptop Battery Status using C#*/ System.Management.ObjectQuery query = new ObjectQuery("Select * FROM Win32_Battery"); ManagementObjectSearcher searcher = new ManagementObjectSearcher(query); ManagementObjectCollection collection = searcher.Get(); foreach (ManagementObject mo in collection) { foreach (PropertyData property in mo.Properties) { Console.WriteLine("Property {0}: Value is {1}", property.Name, property.Value); } } Console.ReadLine(); } |