[C#]使用GetSystemPowerStatus API查看目前電源使用狀態
<td valign="top" width="499">表示目前充電狀態。
<br />1為High(66%以上電力)、2為Low(33%以上電力)、4為Critical(5%以下電力)、8為Charging、128為NoBattery、255為UnKnow</td>
</tr>
<tr>
<td valign="top" width="200">BatteryFullLifeTime</td>
<td valign="top" width="499">表示充滿電力可使用多久時間(-1為不詳)。</td>
</tr>
<tr>
<td valign="top" width="200">BatteryLifePercent</td>
<td valign="top" width="499">表示電力剩餘多少百分比,其正常值為0~100,255為電力不詳。</td>
</tr>
<tr>
<td valign="top" width="200">BatteryLifeTime</td>
<td valign="top" width="499">表示剩餘電力可使用多久時間(-1為不詳)。</td>
</tr>
<tr>
<td valign="top" width="200">ACLineStatus</td>
<td valign="top" width="499">表示電源狀態。
<br />0為offline、1為online、255為unknow。</td>
</tr>
namespace Battery { [Flags] public enum BatteryChargeStatus : byte { High = 1, Low = 2, Critical = 4, Charging = 8, NoSystemBattery = 128, Unknown = 255 }
public enum PowerLineStatus : byte
{
Offline = 0,
Online = 1,
Unknown = 255
}
class PowerStatus
{
[DllImport("kernel32", EntryPoint = "GetSystemPowerStatus")]
private static extern void GetSystemPowerStatus(ref SystemPowerStatus powerStatus);
private struct SystemPowerStatus
{
public PowerLineStatus PowerLineStatus;
public BatteryChargeStatus BatteryChargeStatus;
public Byte BatteryLifePercent;
public Byte Reserved;
public int BatteryLifeRemaining;
public int BatteryFullLifeTime;
}
private SystemPowerStatus _powerStatus;
public PowerLineStatus PowerLineStatus
{
get
{
return _powerStatus.PowerLineStatus;
}
}
public BatteryChargeStatus BatteryChargeStatus
{
get
{
return _powerStatus.BatteryChargeStatus;
}
}
public float BatteryLifePercent
{
get
{
return _powerStatus.BatteryLifePercent;
}
}
public int BatteryLifeRemaining
{
get
{
return _powerStatus.BatteryLifeRemaining;
}
}
public int BatteryFullLifeTime
{
get
{
return _powerStatus.BatteryFullLifeTime;
}
}
public PowerStatus()
{
UpdatePowerInfo();
}
public void UpdatePowerInfo()
{
GetSystemPowerStatus(ref _powerStatus);
}
}
}
namespace BatteryPower { public partial class Form1 : Form {
public Form1()
{
InitializeComponent();
}
private void UpdateInfo()
{
Battery.PowerStatus power = new Battery.PowerStatus();
this.tbxPowerStatus.Text = power.PowerLineStatus.ToString();
this.tbxBatteryChargeStatus.Text = power.BatteryChargeStatus.ToString();
this.tbxBatteryFullLifetime.Text = power.BatteryFullLifeTime.ToString();
this.tbxBatteryLifePercent.Text = power.BatteryLifePercent.ToString();
this.tbxBatteryLifeRemaining.Text = power.BatteryLifeRemaining.ToString();
}
private void timer1_Tick(object sender, EventArgs e)
{
UpdateInfo();
}
private void Form1_Load(object sender, EventArgs e)
{
UpdateInfo();
}
}
}