I wanted my program to show a simple dialog form when the battery percentage of my laptop reaches 80%. I've used SystemInformation.PowerStatus.BatteryLifePercent
to achieve the same and have used a timer event to monitor the battery percentage changing while charging or discharging and check for the battery to reach 80% charge using the above mentioned method. Below is my code.
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
Timer1.Enabled = True
TimerChargeMonitor.Interval = 100
TimerChargeMonitor.Enabled = True
End Sub
Private Sub TimerChargeMonitor_Tick(sender As Object, e As EventArgs) Handles TimerChargeMonitor.Tick
If SystemInformation.PowerStatus.BatteryLifePercent = 0.8 Then
NotifBox.Show()
TimerChargeMonitor.Enabled = False
End If
End Sub
The problem is it doesnt work. The dialog form doesnt show up when the battery percentage reaches 80% or any other number.
Your code needs some adjustments:
SystemInformation.PowerStatus.BatteryLifePercent returns a single.
It's better to test it with >= because its value might be slightly different from what you are expecting here.
Then, you have to stop your timer before showing a MessageBox (if that is what NotifBox.Show() is).
So your code would be:
If SystemInformation.PowerStatus.BatteryLifePercent >= 0.8 Then
TimerChargeMonitor.Stop()
NotifBox.Show()
End If
As a note, the tick interval seems way too low for this application.
Maybe set it to TimerChargeMonitor.Interval = 5000
(I don't know what the other timer is for, here).
Related
I am making a game for a piece of coursework and I have came across a problem. It is a very simplistic game. An enemy will spawn (Picture Box) and you will shoot it (Left Click) to make it die (Disappear). I want the user to lose 5 health for every 3 seconds the enemy is alive. The only way I could think of doing this is by using a timer and a text box. The timer is disabled when the game begins. When the enemy spawns the timer becomes enabled and the text box begins to increment by one every second. When the user kills the enemy the timer becomes disabled again and the text box is reset to 0. Now all I need to do is for the user to lose health every 3 seconds the enemy is alive. The following code is the code I currently have:
Private Sub timerenabled()
If PicBoxEnemy.Visible = True Then
Timer2.Enabled = True
Else
Timer2.Enabled = False
TxtBox.Text = 0
End If
End Sub
Private Sub Timer2_Tick(sender As Object, e As EventArgs) Handles Timer2.Tick
TxtBox.Text = TxtBox.Text + 1
End Sub
Private Sub checkvalue()
Dim x As Integer
x = TxtBox.Text / 3
If CInt(x) Then
Do
health = health - 5
Loop Until health = 0
End If
End Sub
Any other more efficient ways to do this would be appreciated. I hope you understand what I am trying to do.
First and foremost, Stack Overflow isn't really a tutorial site, but I can't resist answering you.
OK there are to be honest several issues with your code. But first, to your question. Instead of using a TextBox, Use a Label. The textbox could be modified by the user. This brings me to one of the issues.
First, It's really bad practice to use controls as the repository for data. You have the right idea with the variable health.
Second. Turn on Option Strict in Visual studio's settings. While you are there, make sure that Explicit is on, Compare is Binary, and Infer is Off.
Have a look at this Stack Overflow answer
Changing these options will mean that you will write less buggy code , but on the downside, you will need to write a bit more.
Finally take a little time to choose meaningful names for your variables and objects, it will make it a lot easier to remember what they're for. For example call Timer2 something like TmrGameRunning - Not something like TmrGR in six months time you probably wont remember what a name like that means. :-)
You'll need to create a label called LblHealth. I'm assuming that the TxtBox control can be discarded as it is merely there to count timer ticks. You don't need it. Also assuming that you added the timer as a Timer control, in the timer's properties, just set the interval to 3000 which is the number of milliseconds between ticks = 3 seconds
Have a look at the modified code and the comments for explanations
Public Class Form1
Dim health As Integer
' This will be the variable that note if your player is alive or dead .. True if alive, False if dead
Dim PlayerAlive As Boolean = True
'This is slightly different to your code. In VB, there is an event that will fire when the
'visibility of a textbox changes. The following method will execute when this happens. Just like code
'that you would write when you're handling a button.click event
Private Sub PicBoxEnemy_VisibleChanged(sender As Object, e As EventArgs) Handles PicBoxEnemy.VisibleChanged
If PicBoxEnemy.Visible = True Then
Timer2.Enabled = True
Else
Timer2.Enabled = False
End If
End Sub
'This is a modified version of your timer tick - Don't forget to change the timer .Interval property
'to 3000
Private Sub Timer2_Tick(sender As Object, e As EventArgs) Handles Timer2.Tick
health = health - 5
'This will change the text of the label to whatever your player's health is and the line below
'will force the label to update
LblHealth.Text = health.ToString
LblHealth.Update()
'Also while the timer is ticking the method below will check the health of your player and decide if
'they are dead or not. If they are, the timer is disabled and the PlayerDead method is called.
AliveOrDead()
End Sub
Private Sub AliveOrDead()
If health <= 0 Then
Timer2.Enabled = False
PlayerDead()
End If
End Sub
'This will be the method that executes when the player is dead. You'll need to add your own code
'for this of course, depending on what you want to do.
Private Sub PlayerDead()
'code here for what happens at the end of the game
End Sub
End Class
Hint. You'll probably need a button control and a Button.Click event handler method to start the game, a way of making the PictureBox visible (possibly at random intervals) while the game is running,(dont forget to stop this timer when the PictureBox is made visible), and finally an event handler that is called when you click on the picture to make it invisible(and stop the timer that reduces health)
I would like to display a sentence in a text box at a 5 specific times during the day automatically. for example:
at 5:30 AM,
Textbox1.text = "breakfast"
at 7:30 AM
textbox1.text = "leave for school",
etc.
a timer can just start when the application is launched, although it needs to refer to the local time or some constant time as the program needs to output at the same time each day of the week without me having to change it manually.
The proper way to do it is something like this:
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
'Set the interval at startup.
Timer1.Interval = CInt(GetNextNotificationTime().Subtract(Date.Now).TotalMilliseconds)
End Sub
Private Sub Timer1_Tick(sender As Object, e As EventArgs) Handles Timer1.Tick
'Set the interval at each notification.
Timer1.Interval = CInt(GetNextNotificationTime().Subtract(Date.Now).TotalMilliseconds)
'Not sure whether this is required when the Interval changes or not.
Timer1.Stop()
Timer1.Start()
'Do the work here.
End Sub
Private Function GetNextNotificationTime() As Date
'...
End Function
How you implement that GetNextNotificationTime method depends on how the notification times are stored. The Timer will then Tick only when a notification is due.
You can still do this with a Timer and you wouldn't have to do any math...
Every time the Timer raises a Tick event, you check the value of: System.DateTime.Today.Now.ToString("HH:mm"). If it is equal to your preset time, change the text in the TextBox
Hello I am a novice / mediocre VB programmer and I made a timer that simply need to update it self every second.
I started having doubts about weather or not it was working so I applied a msg box to my timers code it went off every second updating it self but the progress bar wont? why?
Dim power As PowerStatus = SystemInformation.PowerStatus
Dim percent As Single = power.BatteryLifePercent
Private Sub Timer1_Tick(sender As Object, e As EventArgs) Handles Timer.Tick
ProgressBar1.Value = percent * 100
Label1.Text = percent * 100
End Sub
I have a power status and percent that takes the status and turn into a usable percentage then the progress bar uses that percentage but isnt updating like the msgBOX does why?
Well, your timer is probably working well and all, but you don't show where/how you get the updated value of SystemInformation.PowerStatus.BatteryLifePercent.
Maybe you're doing this somewhere else in your code, but as it is posted, you're always displaying the same value, so of course the progressbar is never going to change.
From what I can see from your question, everything should be working ok but I cant see that you have added Timer1.Interval = 1000 however you may have but this with the designer and not the coding side, however nevertheless here is how I did this project so you could see my working example just so you can be sure, If you have any problems let me know and i will do my best to help you out :)
Public Class Form1
Dim Timer1 As New Timer
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
Timer1.Enabled = True
Timer1.Interval = 1000
AddHandler Timer1.Tick, AddressOf Timer1_Tick
Timer1.Start()
End Sub
Private Sub Timer1_Tick()
Dim POWER As PowerStatus = SystemInformation.PowerStatus
Dim PERCENT As Single = POWER.BatteryLifePercent
Dim ONCHARGE As PowerStatus = SystemInformation.PowerStatus
ProgressBar1.Value = PERCENT * 100
Label1.Text = "Power Remaining: " & PERCENT * 100 & "%"
If ONCHARGE.PowerLineStatus = PowerLineStatus.Online Then
Label2.Text = "Currently: Charging"
Else
Label2.Text = "Currently: Not Charging"
End If
End Sub
End Class
I added a Progressbar and two labels to the form, one of which is the computer battery and another of which will tell the user if the cable is unplugged in or not, i know you didnt ask for the cable status but i added it just incase you needed it :)
Happy Coding
Okay, so I am making a game, like cookie clicker, or in my case - http://www.silvergames.com/poop-clicker (don't ask...), so that when you click on the icon in the center, it changes the total value by adding 1. On the side, you have a picture which you click to increase the amount it generates automatically every second.
At the moment I have it like this:
The timer tics every second. If the total amount > the cost of upgrade then it shows the picture of the thing you click to upgrade.
When you click that picture -
The cost is taken away from the total amount.
It changes the amount of times you have used that upgrade by +1.
The automatic upgrades per second is changed by +1.
The Cost is increased by 10.
What is happening is that I click the icon in the middle say 5 times (very quickly) and it only comes up with a total of 3. That in itself is a problem, but the even worse problem is that it shows the picture to click, when i told it to only show when the total value was > 10 (the cost of the upgrade).
I am really confused, and any help will be much appreciated.
Thanks
SkySpear
PS. Here's the Code -
Public Class Form1
Private Sub picPoop_Click(sender As Object, e As EventArgs) Handles picPoop.Click
lblPoops.Text = lblPoops.Text + 1
End Sub
Private Sub picCursor_Click(sender As Object, e As EventArgs) Handles picCursor.Click
lblPoops.Text = lblPoops.Text - lblCursorCost.Text
lblCursorAmmount.Text = lblCursorAmmount.Text + 1
lblPoopsPerSec.Text = lblPoopsPerSec.Text + 1
lblCursorCost.Text = lblCursorCost.Text + 10
End Sub
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
lblCursorAmmount.Text = 0
lblCursorCost.Text = 10
lblBabyAmmount.Text = 0
lblBabyCost.Text = 100
lblBowlAmmount.Text = 0
picCursor.Hide()
tmrSec.Start()
End Sub
Private Sub tmrSec_Tick(sender As Object, e As EventArgs) Handles tmrSec.Tick
If lblPoops.Text > lblCursorCost.Text Then picCursor.Show()
End Sub
End Class
Again, don't ask where this ridiculous idea came from, I can assure you it wasn't mine.
Your main problem with this is that in your Timer sub, you are comparing text to text. In this case, a value of "3" > "21", since text comparisons work on a char by char basis. When this happens, your pictureBox is being shown. As others suggested, you can use any of the string to numeric conversion functions in your timer event to make this work better.
A slightly better approach would be to declare some class level numeric variables that hold each individual value and displays them when needed. As an example
numPoops += 1
lblPoops.Text = numPoops
This will make sure that all math will work correctly.
You are dealing with the Value of the textboxes, not the Text in it.
You should enclose each textbox with VAL() to get its exact value as a number.
Private Sub picPoop_Click(sender As Object, e As EventArgs) Handles picPoop.Click
lblPoops.Text = VAL(lblPoops.Text) + 1
End Sub
Private Sub picCursor_Click(sender As Object, e As EventArgs) Handles picCursor.Click
lblPoops.Text = VAL(lblPoops.Text) - VAL(lblCursorCost.Text)
lblCursorAmmount.Text = VAL(lblCursorAmmount.Text) + 1
lblPoopsPerSec.Text = VAL(lblPoopsPerSec.Text) + 1
lblCursorCost.Text = VAL(lblCursorCost.Text) + 10
End Sub
Private Sub tmrSec_Tick(sender As Object, e As EventArgs) Handles tmrSec.Tick
If VAL(lblPoops.Text) > VAL(lblCursorCost.Text) Then picCursor.Show()
End Sub
I would like to stop the timer whenever a mouse stops moving inside a groupbox
As of now, I start the timer when the mouse hover at the groupbox and stops it when it leaves the group box.
Private Sub gbxMouseMap_MouseHover(sender As Object, e As System.EventArgs) Handles gbxMouseMap.MouseHover
Timer.Start()
End Sub
Private Sub gbxMouseMap_MouseLeave(sender As Object, e As System.EventArgs) Handles gbxMouseMap.MouseLeave
Timer.Stop()
End Sub
In the MouseMove event set a class varible named LastMoveTime to the current timer elapsed time. In the MouseHover event check to see if LastMoveTime has reached the timeout period, if so stop the timer.
I will get you started...
Private LastMoveTime As DateTime
Private MouseTimeoutMilliseconds as Integer = 500
'put inside hover
If LastMoveTime.AddMilliseconds(MouseTimeoutMilliseconds) < Now Then
Timer.Stop()
Else
Timer.Start()
End if
To prevent having to handle this for many controls you can rearrange things a bit and cache the information needed to know if cursor has moved and how long the idle time is, to do this you need a Point variable and a Date variable. The Timer needs to tick all the time. In addition, to balance the cursor Show/Hide calls you need a variable to keep track of its visibility state. Here is the complete code sample:
Private loc As Point, idle As Date, hidden As Boolean,
Private Sub Timer1_Tick(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Timer1.Tick
If loc <> Cursor.Position Then
If hidden Then
Cursor.Show()
hidden = False
End If
loc = Cursor.Position
idle = Date.Now
ElseIf Not hidden AndAlso (Date.Now - idle).TotalSeconds > 3 Then
Cursor.Hide()
hidden = True
End If
End Sub
This Timer can tick each 1/2-1 seconds depending on how responsive you want it, the idle time is set to 3 seconds. The code should be easy to understand when you read it and give it some thought, if not ask