VB.NET电池百分比显示代码无法实时更新,求问题排查
问题原因与修复方案
你的代码核心问题是只在程序启动时获取了一次电池状态数据,之后Timer触发时一直复用旧数据,自然不会实时更新。
具体来说,你把psBattery和perFull定义为Form级变量,仅在程序初始化时赋值一次。Timer的Tick事件里没有重新读取系统当前的电池状态,所以不管电池电量怎么变,显示的都是启动时的数值。
修复代码
把获取电源状态的逻辑移到TimerBattery_Tick事件内部,确保每次触发都读取最新数据:
Private Sub TimerBattery_Tick(sender As Object, e As EventArgs) Handles TimerBattery.Tick ' 每次Tick都重新获取最新的电源状态 Dim psBattery As PowerStatus = SystemInformation.PowerStatus Dim perFull As Single = psBattery.BatteryLifePercent ' 处理进度条数值,避免超过最大值 ProgressBar1.Value = If(perFull * 100 >= 100, 100, CInt(perFull * 100)) ' 更新标签文本 Dim batteryPercent As Integer = Math.Round(perFull * 100) If psBattery.PowerLineStatus = PowerLineStatus.Online Then LabelBatt.Text = $"Battery {batteryPercent}%" LabelBatt2.Text = $"{batteryPercent}%, charging" Else LabelBatt.Text = $"Battery {batteryPercent}%" LabelBatt2.Text = $"{batteryPercent}%, not charging" End If End Sub
额外注意事项
- 确保Timer控件的
Enabled属性设为True,或者在Form_Load事件里调用TimerBattery.Start()启动定时器 - 可以根据需求调整Timer的
Interval属性(单位毫秒),比如设为1000表示每秒更新一次
内容的提问来源于stack exchange,提问作者Fabieen Rae
相关产品推荐
相关产品推荐

