You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

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

额外注意事项

  1. 确保Timer控件的Enabled属性设为True,或者在Form_Load事件里调用TimerBattery.Start()启动定时器
  2. 可以根据需求调整Timer的Interval属性(单位毫秒),比如设为1000表示每秒更新一次

内容的提问来源于stack exchange,提问作者Fabieen Rae

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.21 19:27:16