What I'm trying to do is write a script that creates a message box/popup when my computer's battery falls to 20%. I want the message box to appear only once—it shouldn't show up again after I click "OK" unless I charge my computer and let it drain to 20% again.
The problem is that the code I have causes message boxes to appear every few minutes while my battery is below 20%. My code is below:
set oLocator = CreateObject("WbemScripting.SWbemLocator")
set oServices = oLocator.ConnectServer(".","root\wmi")
set oResults = oServices.ExecQuery("select * from batteryfullchargedcapacity")
for each oResult in oResults
iFull = oResult.FullChargedCapacity
next
while (1)
set oResults = oServices.ExecQuery("select * from batterystatus")
for each oResult in oResults
iRemaining = oResult.RemainingCapacity
bCharging = oResult.Charging
next
iPercent = Round((iRemaining / iFull) * 100)
if iRemaining and not bCharging and (iPercent < 21) and (iPercent > 10) Then msgbox "Your battery power is low (" & iPercent & "%). If you need to continue using your computer, either plug in your computer, or shut it down and then change the battery.",vbInformation, "Your battery is running low."
wscript.sleep 30000 ' 5 minutes
wend
I'm very new to VBScript (and programming in general), so I'm not really sure how to fix this.
CodePudding user response:
You need to have a flag for example a variable called iShow. It starts with value 1 (message can popup), after you click OK, iShow will be zero (don't show again). The next time this flag will have value 1 is when the batery is more than 21%, so when it fall again to less 21% the message can popup again but just once. Here is the code:
set oLocator = CreateObject("WbemScripting.SWbemLocator")
set oServices = oLocator.ConnectServer(".","root\wmi")
set oResults = oServices.ExecQuery("select * from batteryfullchargedcapacity")
for each oResult in oResults
iFull = oResult.FullChargedCapacity
next
Dim iShow
iShow=1
while (1)
set oResults = oServices.ExecQuery("select * from batterystatus")
for each oResult in oResults
iRemaining = oResult.RemainingCapacity
bCharging = oResult.Charging
next
iPercent = Round((iRemaining / iFull) * 100)
if (iPercent>21) then iShow=1
if (iShow=1) and not bCharging and (iPercent < 21) Then
msgbox "Your battery power is low (" & iPercent & "%). If you need to continue using your computer, either plug in your computer, or shut it down and then change the battery.",vbInformation, "Your battery is running low."
iShow=0
end if
wscript.sleep 30000 ' 5 minutes
wend