0

this is my code, i using timer and button to trigger the event

using System.Management;
using System.Management.Instrumentation;
namespace battery_efficiency_meter
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void Remaining_Timer_Tick(object sender, EventArgs e)
        { 
           try
            {               
              // Create a ManagementObjectSearcher object to run WMI queries             
                 ManagementObjectSearcher searcher = new ManagementObjectSearcher("SELECT * FROM Win32_Battery WHERE DeviceID = '1234****9Ice LakeLi-ion Battery'");

              // Looping each query result
                foreach (ManagementObject obj in searcher.Get())
                {
                     // Get the remaining and full battery capacity values ​​in mAh
                     int remainingCapacity = (int)(uint)obj["RemainingCapacity"];
                     int fullChargeCapacity = (int)(uint)obj["FullChargeCapacity"];

                     // count battery 
                     double batteryPercentage = (double)remainingCapacity / fullChargeCapacity * 100;

                     // show battery percent on string format
                     Percentage.Text = string.Format("{0:0.000}%", batteryPercentage);
                }
           }
           catch (ManagementException ex)
            {
                // Tampilkan pesan error jika terjadi exception
                MessageBox.Show("Error: " + ex.Message + "\n\n" + ex.StackTrace);
            }
//button Start_But to trigger the event
int FN = 1;
        System.Diagnostics.Stopwatch stopwatch = new System.Diagnostics.Stopwatch();
        private void Start_But_Click(object sender, EventArgs e)
        {                        
            if (FN == 1)
            {                
                Stopwatch_Timer.Start();
                stopwatch.Start();                
                PowerStatus ps = SystemInformation.PowerStatus;                
                listBox2.Items.Add(FN++ + ".  " + lbl_Time.Text + " =  " + Percentage.Text);

                var batteryLifePercent = Convert.ToInt32(ps.BatteryLifePercent);
                chart1.Series["Battery"].Points.AddXY(FNChart, ps.BatteryLifePercent * 100);                
                
            }
            else
            {
                Stopwatch_Timer.Start();
                stopwatch.Start();
                
            }
            Start_But.Enabled = false;
            Pause_But.Enabled = true;
            Reset_But.Enabled = true;
            Record_But.Enabled = true;
            write_data.Enabled = true;

        }

i have done :

  1. add using System.Management; as reference
  2. add using System.Management.Instrumentation; as reference
  3. run visual studio 2022 as administrator
  4. add this <requestedPrivileges xmlns="urn:schemas-microsoft-com:asm.v3"> <requestedExecutionLevel level="requireAdministrator" uiAccess="false" /> </requestedPrivileges> to app.config or web.config
  5. add my battery id to my code

but when i enter my battery id, its always catch some error. which part should i add or fix?

  • Why do you have this: `var batteryLifePercent = Convert.ToInt32(ps.BatteryLifePercent);`? It's a float value, in the range (`0.0` : `1.0`); you have to multiply by 100 to get the percentage -- Since you're using `SystemInformation.PowerStatus` (which calls [GetSystemPowerStatus()](https://learn.microsoft.com/en-us/windows/win32/api/winbase/nf-winbase-getsystempowerstatus) and it's always up to date, each time you read it), what do you actually need `System.Management` for (which also requires admin access)? -- You're not using `System.Management.Instrumentation` – Jimi Jan 04 '23 at 15:42
  • @jimi `var batteryLifePercent = Convert.ToInt32(ps.BatteryLifePercent);` i forget to erase this cause i use this before ```PowerStatus ps = SystemInformation.PowerStatus; PercentageBar.Value = (int)(ps.BatteryLifePercent * 100); if (ps.BatteryLifeRemaining < 0) TimeLabel.Text = "Charging"; else TimeLabel.Text = "Remaining Time = " + new TimeSpan(0, 0, ps.BatteryLifeRemaining); Percentage.Text = string.Format($"{ps.BatteryLifePercent * 100} %"); ``` at my timer – Irvan_prima Jan 04 '23 at 15:56

0 Answers0