在winforms中显示电池状态

本文关键字:状态 显示 winforms | 更新日期: 2023-09-27 18:02:48

我一直在使用perfmon创建一个winform应用程序。我发现电池状态不工作,因为它是窗口管理的一部分。所以我决定走wmi路线。

所以我的问题是,当我把电池状态放在标签中,如下所示:

private void BatteryStatus()
    {
        System.Management.ManagementClass wmi  = new System.Management.ManagementClass("Win32_Battery");
        var allBatteries = wmi.GetInstances();
        foreach (var battery in allBatteries)
        {
            int estimatedChargeRemaining = Convert.ToInt32(battery["EstimatedChargeRemaining"]);
            if (estimatedChargeRemaining == 100)
            {
                label13.Text = "Remaining:" + "  " + estimatedChargeRemaining + "  " + "%";
            }
        }

    }

剩余电荷完美显示。我的问题是,是否有一种方法,我可以只有一个if statement调用电池状态从100到1

或者我现在做的方式是我必须再做99个if statements吗?

这是我自定义构建的性能监视器的一部分。如果perfmon允许使用计数器,就会容易一些。这是我能想到的获取电池状态的唯一方法,例如:

Charge Rate
Discharge Rate
Remaining Capacity
Voltage

我一直用电池状态标签做if statements。在我开始做更多的if statements之前,我想确定有没有更简单的方法?

***********更新************我想明白了。谢谢大家的帮助。

在winforms中显示电池状态

我想你应该这样做:

private void BatteryStatus()
{
    System.Management.ManagementClass wmi  = new System.Management.ManagementClass("Win32_Battery");
    var allBatteries = wmi.GetInstances();
    foreach (var battery in allBatteries)
    {
        int estimatedChargeRemaining = Convert.ToInt32(battery["EstimatedChargeRemaining"]);           
        label13.Text = "Remaining:" + "  " + estimatedChargeRemaining + "  " + "%";
    }
}

不需要and if语句,无论百分比是多少,标签都会被更新。

在问题的第二部分,你说你想显示"电池状态",然后你可以像这样使用if:

  private void BatteryStatus()
 {
    System.Management.ManagementClass wmi  = new System.Management.ManagementClass("Win32_Battery");
    var allBatteries = wmi.GetInstances();
    foreach (var battery in allBatteries)
    {
        int estimatedChargeRemaining = Convert.ToInt32(battery["EstimatedChargeRemaining"]); 
        string Status = "";    
        if(estimatedChargeRemaining < 15) Status = "Critical";
        else  if(estimatedChargeRemaining < 35) Status = "Low";
        else  if(estimatedChargeRemaining < 60) Status = "Regular";
        else  if(estimatedChargeRemaining < 90) Status = "High";
        else Status = "Complete";
        label13.Text = "Remaining:" + "  " + estimatedChargeRemaining + "  " + "% | Status: " + Status;
    }
}
 private void BatteryStatus()
    {
        System.Management.ManagementClass wmi  = new System.Management.ManagementClass("Win32_Battery");
        var allBatteries = wmi.GetInstances();
        foreach (var battery in allBatteries)
        {
            int estimatedChargeRemaining = Convert.ToInt32(battery["EstimatedChargeRemaining"]);
            label13.Text = "Remaining" + "  " + estimatedChargeRemaining.ToString() + "  " + "%";
            if (estimatedChargeRemaining < 15 )
            {
                label13.ForeColor = Color.Red;
            }
        }

    }