摘自 http://blog.csdn.net/li0531/article/details/8818243
同时只在右上角显示一个 Label 控件,因此代码量精简了很多。
[DllImport("coredll")] private static extern int GetSystemPowerStatusEx(SYSTEM_POWER_STATUS_EX lpSystemPowerStatus, bool fUpdate); [DllImport("coredll")] public static extern void SystemIdleTimerReset(); private SYSTEM_POWER_STATUS_EX status = new SYSTEM_POWER_STATUS_EX(); /// <summary> ///// 是否充电状态 ///// </summary> //private State AState = State.Normal; /// <summary> /// 电池当前状态 Charge:充电中;UnderCharge:电量不足;Normal:电池正常使用. /// </summary> public enum State { /// <summary> /// 充电中 /// </summary> Charge, /// <summary> /// 充电不足 /// </summary> UnderCharge, /// <summary> /// 正常状态 /// </summary> Normal, /// <summary> /// 充电完成 /// </summary> ChargeFinally }; private class SYSTEM_POWER_STATUS_EX { public byte ACLineStatus = 0; public byte BatteryFlag = 0; public byte BatteryLifePercent = 0; public byte Reserved1 = 0; public uint BatteryLifeTime = 0; public uint BatteryFullLifeTime = 0; public byte Reserved2 = 0; public byte BackupBatteryFlag = 0; public byte BackupBatteryLifePercent = 0; public byte Reserved3 = 0; public uint BackupBatteryLifeTime = 0; public uint BackupBatteryFullLifeTime = 0; } /// <summary> /// 创建电源指示 /// </summary> private void GetBatteryState() { if (GetSystemPowerStatusEx(status, false) == 1) { if (status.BatteryLifePercent >= 95) { labBattery.Text = "100"; labBattery.ForeColor = Color.Green; } else if (status.BatteryLifePercent <= 20) { if (status.ACLineStatus == 1) labBattery.Text = status.BatteryLifePercent.ToString() + " +"; else labBattery.Text = "! " + status.BatteryLifePercent.ToString(); labBattery.ForeColor = Color.Red; } else { labBattery.Text = status.BatteryLifePercent.ToString() + (status.ACLineStatus == 1 ? " +" : ""); labBattery.ForeColor = Color.Blue; } } }
我是在 Timer 控件下以 10m 的频率调用这个方法的。
时间: 2024-10-14 13:25:25