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 :
- add using
System.Management;
as reference - add using
System.Management.Instrumentation;
as reference - run visual studio 2022 as administrator
- add this
<requestedPrivileges xmlns="urn:schemas-microsoft-com:asm.v3"> <requestedExecutionLevel level="requireAdministrator" uiAccess="false" /> </requestedPrivileges>
to app.config or web.config - 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?