我一直在使用perfmon创建一个winform应用程序。我发现电池状态不起作用,因为它是Windows管理的一部分。所以我决定走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
。在我再做99次if statements
之前,我想确定没有更简单的方法吗?
***********更新************ 我想到了。感谢帮助的人的帮助。
答案 0 :(得分:2)
我想你要做的就是:
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 + " " + "%";
}
}
无需和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;
}
}
答案 1 :(得分:0)
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;
}
}
}