Getting Battery Status In Windows 10

The Battery Class provides information about a battery controller that is currently connected to the device,

Step 1: Open a blank app and add a Button and a TextBlock either from the toolbox or by copying the following XAML code into your grid.

  1. <StackPanel>  
  2.     <TextBlock Text="Battery Status" Margin="10" FontSize="20"></TextBlock>  
  3.     <StackPanel Margin="10,20,0,0">  
  4.         <Button Name="getBatteryStatus" Height="40" Width="140" Content="Get Battery Status" Click="getBatteryStatus_Click"></Button>  
  5.         <TextBlock Name="batteryStatus" Margin="10,20,0,0" Height="50" FontSize="20"></TextBlock>  
  6.     </StackPanel>  
  7. </StackPanel>       
  

Step 2: Add the following namespaces to your project which is needed in further C# code.

  1. using Windows.Devices.Enumeration;  
  2. using Windows.Devices.Power;  

Step 3: Copy and paste the following code to the cs page which will be called on button click event and the battery status in the TextBlock.

  1. private async void getBatteryStatus_Click(object sender, RoutedEventArgs e)  
  2. {  
  3.     var deviceInfo = await DeviceInformation.FindAllAsync(Battery.GetDeviceSelector());  
  4.     foreach (DeviceInformation device in deviceInfo)  
  5.     {  
  6.         var battery = await Battery.FromIdAsync(device.Id);  
  7.         var report = battery.GetReport();  
  8.   
  9.         double maximum = Convert.ToDouble(report.FullChargeCapacityInMilliwattHours);  
  10.         double remaining = Convert.ToDouble(report.RemainingCapacityInMilliwattHours);  
  11.         double percentage = ((remaining / maximum) * 100);  
  12.         int per = Convert.ToInt32(percentage);  
  13.   
  14.         batteryStatus.Text = "You have " + per.ToString() + "% battery remaining" ;             
  15.     }  
  16. }  
Here we are calculating the percentage by using the FullChargeCapacity and RemainingCapacity values.

Step 4: Run your application and test yourself.


Similar Articles