I made a program with Visual Studio to display battery percentage using a Label and ProgressBar, the problem I had is that the battery percentage isn't updated in real time although I already put TimerBattery.Tick()
in Form_Load
, I have to relaunch my app to update the information. Any idea what's wrong with my code?
Dim psBattery As PowerStatus = SystemInformation.PowerStatus
Dim perFull As Single = psBattery.BatteryLifePercent
Private Sub TimerBattery_Tick(sender As Object, e As EventArgs) Handles TimerBattery.Tick
If perFull * 100 >= 100 Then
ProgressBar1.Value = 100
ElseIf perFull * 100 < 100 Then
ProgressBar1.Value = perFull * 100
End If
If psBattery.PowerLineStatus = PowerLineStatus.Online Then
LabelBatt.Text = "Battery " & perFull * 100 & "%"
LabelBatt2.Text = perFull * 100 & "%, charging"
ElseIf psBattery.PowerLineStatus = PowerLineStatus.Offline Then
LabelBatt.Text = "Battery " & perFull * 100 & "%"
LabelBatt2.Text = perFull * 100 & "%, not charging"
End If
End Sub
You need to move at least the line that initializes the perFull variable inside the Tick event. Otherwise the perFull value is calculated just one time when you open the form class.
Dim psBattery As PowerStatus = SystemInformation.PowerStatus
Private Sub TimerBattery_Tick(sender As Object, e As EventArgs) Handles TimerBattery.Tick
' Now at each Tick event you read the PowerStatus value and
' execute the Tick logic with the correct value
Dim perFull As Single = psBattery.BatteryLifePercent
If perFull * 100 >= 100 Then
ProgressBar1.Value = 100
ElseIf perFull * 100 < 100 Then
ProgressBar1.Value = perFull * 100
End If
If psBattery.PowerLineStatus = PowerLineStatus.Online Then
LabelBatt.Text = "Battery " & perFull * 100 & "%"
LabelBatt2.Text = perFull * 100 & "%, charging"
ElseIf psBattery.PowerLineStatus = PowerLineStatus.Offline Then
LabelBatt.Text = "Battery " & perFull * 100 & "%"
LabelBatt2.Text = perFull * 100 & "%, not charging"
End If
End Sub