BOOL WINAPI GetSystemPowerStatus(__out LPSYSTEM_POWER_STATUS lpSystemPowerStatus);
typedef struct _SYSTEM_POWER_STATUS { BYTE ACLineStatus; BYTE BatteryFlag; BYTE BatteryLifePercent; BYTE Reserved1; DWORD BatteryLifeTime; DWORD BatteryFullLifeTime; } SYSTEM_POWER_STATUS, *LPSYSTEM_POWER_STATUS;
using System.Collections.Generic; using System.Linq; using System.Text; using System.Runtime.InteropServices; 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); } } }
using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Windows.Forms; 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(); } } }