Timer not stopping VB.NET - vb.net

I'm making a simple Windows Forms App with Visual Studio 2019. I want to use a timer and a progress bar but i can't make the timer stop.
I've tried Timer1.Stop() and Timer1.Enabled = False but neither of them have worked. The timer waits 1 second.
Here's the full code:
(it has changed a lot but I still have the problem)
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
If Button1.Text = "Stop" Then
ProgressBar1.Value = 0
Timer1.Enabled = False
End If
Button1.Text = "Stop"
Timer1.Enabled = True
Cursor = Cursors.AppStarting
End Sub
Private Sub Timer1_Tick(sender As Object, e As EventArgs) Handles Timer1.Tick
If Timer1.Enabled = True Then
ProgressBar1.Increment(1)
Else
ProgressBar1.Value = 0
End If
If ProgressBar1.Value = 100 Then
Timer1.Stop()
Button1.Text = "Done!"
End If
End Sub

I strongly suggest that you use a CheckBox rather than a Button. If you set the Appearance to Button then it will look just like a regular Button but you can use the Checked property to represent state. The control will appear depressed when Checked is True. You can then use code like this:
Private Sub CheckBox1_CheckedChanged(sender As Object, e As EventArgs) Handles CheckBox1.CheckedChanged
Timer1.Enabled = CheckBox1.Checked
CheckBox1.Text = If(CheckBox1.Checked, "Stop", "Start")
End Sub
Private Sub Timer1_Tick(sender As Object, e As EventArgs) Handles Timer1.Tick
ProgressBar1.PerformStep()
If ProgressBar1.Value = ProgressBar1.Maximum Then
CheckBox1.Checked = False
End If
End Sub

Related

Run timer in background in visual basic form

first I'm new in this, and I have this code that shows a prompt to restart or postpone the restart for a while, the issue is that i want to hide the message and bring it back after the time specified by the user.
I'm using a "visual basic form" and the time that restart will be postponed it's selected from a "ComboBox"
My code is as follows.
Imports System.Management
Imports System.Security.Permissions
Imports System
Imports System.IO
Imports System.Collections
Imports System.SerializableAttribute
Public Class Form2
Dim PostponeReboot As Integer = 50
Private Const CP_NOCLOSE_BUTTON As Integer = &H200
Protected Overloads Overrides ReadOnly Property CreateParams() As CreateParams
Get
Dim myCp As CreateParams = MyBase.CreateParams
myCp.ClassStyle = myCp.ClassStyle Or CP_NOCLOSE_BUTTON
Return myCp
End Get
End Property
Private Sub Form2_Load(sender As Object, e As EventArgs) Handles MyBase.Load
Form1.Hide()
Label4.Text = SystemInformation.UserName
Button1.Enabled = False
ComboBox1.Enabled = False
Timer1.Interval = 1000
End Sub
Private Sub CheckBox1_CheckedChanged(sender As Object, e As EventArgs) Handles CheckBox1.CheckedChanged
If CheckBox1.Checked Then
CheckBox2.Enabled = False
Button1.Enabled = True
ComboBox1.Enabled = False
ElseIf CheckBox1.Checked = 0 Then
CheckBox2.Enabled = True
Button1.Enabled = False
ComboBox1.Enabled = False
End If
End Sub
Private Sub CheckBox2_CheckedChanged(sender As Object, e As EventArgs) Handles CheckBox2.CheckedChanged
If CheckBox2.Checked Then
CheckBox1.Enabled = False
ComboBox1.Enabled = True
Button1.Enabled = True
ElseIf CheckBox2.Checked = 0 Then
CheckBox1.Enabled = True
ComboBox1.Enabled = False
Button1.Enabled = False
End If
End Sub
Private Sub ComboBox1_SelectedIndexChanged(ByVal sender As System.Object, e As EventArgs) Handles ComboBox1.SelectedIndexChanged
If ComboBox1.Text = "1 Hora" Then
PostponeReboot = 10
ElseIf ComboBox1.Text = "2 Horas" Then
PostponeReboot = 20
ElseIf ComboBox1.Text = "4 Horas" Then
PostponeReboot = 40
ElseIf ComboBox1.Text = "Seleccione" Then
Button1.Enabled = False
End If
End Sub
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
If CheckBox1.Checked Then
MessageBox.Show("Rebooting")
'Shell("shutdown -r -f -t 60")
Form1.Close()
End
ElseIf CheckBox2.Checked Then
MessageBox.Show(PostponeReboot)
Timer1.Start()
Me.Hide()
End If
If PostponeReboot = 0 Then
Me.Show()
Else
Me.Hide()
End If
End Sub
Private Sub Timer1_Tick(sender As Object, e As EventArgs) Handles Timer1.Tick
PostponeReboot = PostponeReboot - 1
'Label5.Text = PostponeReboot
End Sub
End Class
In the first "If" sentence of below I want to start the timer and hide the form, and in the second "If" i want to bring it back the form, but the form remains hidden.
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
If CheckBox1.Checked Then
MessageBox.Show("Rebooting")
'Shell("shutdown -r -f -t 60")
Form1.Close()
End
ElseIf CheckBox2.Checked Then
MessageBox.Show(PostponeReboot)
Timer1.Start()
Me.Hide()
End If
If PostponeReboot = 0 Then
Me.Show()
Else
Me.Hide()
End If
End Sub
I've tried putting the second "If" sentence in another place but don't work, what I'm doing wrong.
I assume here that your Timer1 class raises the Timer1.Tick event every x time after Timer1.Start() is called. The fact that the form can hide tells me Timer1.Start() isn't a blocking method. As such, your second if statement will be verified right after you hide the form, without waiting for the PostponeReboot variable to reach zero. This particular button handler would then exit and your form would remain hidden. What I see is that you already have an event handler for each tick of your timer. Why not use this handler to verify the state of your PostponeReboot variable?
Private Sub Timer1_Tick(sender As Object, e As EventArgs) Handles Timer1.Tick
PostponeReboot = PostponeReboot - 1
If PostponeReboot = 0 Then
Timer1.Stop() 'I would assume
Me.Show()
End If
End Sub
Although, I would recommend you to try other solutions, like having your timer raise an event only when it reaches the elapsed time (so you don't have to handle each ticks unnecessarily). I would also recommend looking into an Universal Windows App with Toast Notifications as you could set a Notification to appear at a set time (handled by Windows) so that you don't have to have a thread running in the background for this.

How to make a label blink

I have a Stopwatch in my form with Interval = 1000 displayed in the hh:mm:ss format.
When it reaches the 5th second it should start to blink the label background as green but so far I can only make the background color turn to green without any flash.
This is how I turn the background color to green:
Private Sub Timer1_Tick(sender As Object, e As EventArgs) Handles Timer1.Tick
Label1.Text = SW.Elapsed.ToString("hh\:mm\:ss")
If Label1.Text = "00:00:05" Then
Label1.BackColor = Color.Green
End If
End Sub
How do I make the label blink?
You could use a simple Async method to do this.
The following code will give Label1 the effect of flashing. Since we have used While True this will continue indefinitely once you hit "00:00:05".
Private Async Sub Flash()
While True
Await Task.Delay(100)
Label1.Visible = Not Label1.Visible
End While
End Sub
You would call this inside your Timer1_Tick method:
Private Sub Timer1_Tick(sender As Object, e As EventArgs) Handles Timer1.Tick
Label1.Text = SW.Elapsed.ToString("hh\:mm\:ss")
If Label1.Text = "00:00:05" Then
Label1.BackColor = Color.Green
Flash()
End If
End Sub
If you only want to flash a couple of times we can make a simple change to Flash():
Private Async Sub Flash()
For i = 0 To 10
Await Task.Delay(100)
Label1.Visible = Not Label1.Visible
Next
'set .Visible to True just to be sure
Label1.Visible = True
End Sub
By changing the number 10 to a number of your choice you can shorten or lengthen the time taken to flash. I have added in Label1.Visible = True after the For loop just to be sure that we see the Label once the flashing has finished.
You will have to import System.Threading.Tasks to make use of Task.Delay.
You need a label, two textboxes, and a button.
The screen allows you to 'set' a couple of colours - this could be taken further, by adding an Error colour, a Warning colour (where you haven't filled a field in...?) and more.
This colour selection would, in a real application, be done by an admin person, from a separate screen, and stored in the DB.
The timer frequency would also be set in the Admin screen/function.
This particular screen needs the textboxes to be double-clicked, and a colour selected for each one.
The back colour for each box changes. Then press the Start button.
If you press the Start button again, it toggles the timer (on/off)
Public Class Form1
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
' not quite correct for what I want, but close...
' https://bytes.com/topic/visual-basic-net/answers/368433-blinking-text
Me.Label1.Text = "A blinking text box"
Me.Label1.BackColor = TextBox2.BackColor
End Sub
Private Sub Timer1_Tick(sender As Object, e As EventArgs) Handles Timer1.Tick
If Me.Label1.BackColor = TextBox2.BackColor Then
Me.Label1.BackColor = TextBox1.BackColor
Else
Me.Label1.BackColor = TextBox2.BackColor
End If
End Sub
Private Sub TextBox1_MouseDoubleClick(sender As Object, e As MouseEventArgs) Handles TextBox1.MouseDoubleClick
Dim dlg As New ColorDialog()
If dlg.ShowDialog() = DialogResult.OK Then
TextBox1.BackColor = dlg.Color
End If
End Sub
Private Sub TextBox2_MouseDoubleClick(sender As Object, e As MouseEventArgs) Handles TextBox2.MouseDoubleClick
Dim dlg As New ColorDialog()
If dlg.ShowDialog() = DialogResult.OK Then
TextBox2.BackColor = dlg.Color
End If
End Sub
Private Sub btnStart_Click(sender As Object, e As EventArgs) Handles btnStart.Click
Timer1.Enabled = Not Timer1.Enabled
End Sub
End Class
Try to put something like this in Timer1_Tick event handler -
Label1.Visible = Not Label1.Visible
Set the timer to enabled and it will do the job.
If you specify the color when the Text is 00:00:05 then you should also specify what the Backcolor should be when the text is something else i.e 00:00:06
Try this and see if it works:
Private Sub Timer1_Tick(sender As Object, e As EventArgs) Handles Timer1.Tick
Label1.Text = SW.Elapsed.ToString("hh\:mm\:ss")
If Label1.Text = "00:00:05" Then
Label1.BackColor = Color.Green
else
Label1.Backcolor = Color.Yellow '(Change color as needed)
End If
End Sub

GetAsyncKeyState not working with spacebar

So I have a program set up so if checkbox 1 is checked, it starts me.keypreview and starts timer3. Then I have timer 3 checking if Spacebar is held down and if it is, it starts Timer1. For some reason, the code doesnt pick up that spacebar is held down and it detects left click instead, When I tried clicking left click it started timer1.
Here is my code:
Private Sub Timer3_Tick(sender As Object, e As EventArgs) Handles Timer3.Tick
hotkey = GetAsyncKeyState(Keys.Space)
If CBool(hotkey) = True Then
Timer1.Start()
Else
Timer1.Stop()
End If
End Sub
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
If CheckBox1.Checked = True Then
Me.KeyPreview = True
Timer3.Start()
Else
Me.KeyPreview = False
Timer3.Stop()
End If
End Sub
End Class
Can anybody help?

How to generate multiple picture boxes and control them using a timer?

My uni asked us to make a game using VB, and I really don't know much about the language.
I'm trying to make a game where balloons go up to them top of the screen and must be popped before getting there.
Public Class Form1
Private Sub Timer1_Tick(sender As Object, e As EventArgs) Handles Timer1.Tick
If PictureBox1.Top = 0 Then
PictureBox1.Visible = False
Timer1.Enabled = False
End If
PictureBox1.Top = PictureBox1.Top - 1
End Sub
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Timer1.Interval = 1
Timer1.Enabled = True
End Sub
Private Sub PictureBox1_Click(sender As Object, e As EventArgs) Handles PictureBox1.Click
PictureBox1.Visible = False
End Sub
End Class
This is my code so far, when I click the button, the balloon starts to go up, if I click the balloon, it disappears, it also disappears if it reaches the top and the timer stops.
How can I generate more balloons and control them using that timer?
Now all you have let to do is add the functionality of adding more PictureBoxes, maybe a second timer and when you create them use an Addhandler statement to point them the the pbs_Click event that I made and add them to the List I made as well.
Public Class Form1
Private PBs As New List(Of PictureBox)
Private Sub Timer1_Tick(sender As Object, e As EventArgs) Handles Timer1.Tick
For Each pb As PictureBox In PBs
If pb.Top = 0 Then
pb.Visible = False
Timer1.Enabled = False
Else
pb.Top = pb.Top - 1
End If
End Sub
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Timer1.Interval = 1000'ms
Timer1.Enabled = True
End Sub
Private Sub pbs_Click(sender As Object, e As EventArgs)
Dim pb As PictureBox = DirectCast(sender, PictureBox)
PBs.Remove(pb)
End Sub
Private Sub makeNewPB()
Dim pb As New PictureBox
Addhandler pb.Click, AddressOf pbs_Click
'don't forget to make them the size you need
PBs.Add(pb)
End Sub
End Class

how to run this timer in vb.net?

I want a timer to run on a form whose value is derived from a database. for example when i store the value for the timer in a variable, i multiply it by 60000 to convert milliseconds to minutes. Here is the code:
Public Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
Dim x as integer
details = ds.Tables(0).Rows(0).Item("Time")
Timer1.Interval =details * 60000
Timer1.Enabled = True
End Sub()
Private Sub Timer1_Tick(sender As Object, e As EventArgs) Handles Timer1.Tick
seconds.Text = x.ToString
If x= 0 Then
Timer1.Enabled = False
MessageBox.Show("You didn't finish in time.", "Sorry")
Me.Close()
Else
x-= 1
End If
End Sub
When i run this code, the timer runs in the background and when time's up, the form closes. But it doesn't show in the label seconds when timer is ticking. I hope you get what I mean :)
If you want the label to tick the seconds down to 0, you need the timer interval to be 1000, no matter how long you want this to run for.
Public Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
details = ds.Tables(0).Rows(0).Item("Time")
Timer1.Interval =1000
endTime = DateTime.Now.AddMinutes(details)
Timer1.Enabled = True
End Sub()
Dim endTime As DateTime
Private Sub Timer1_Tick(sender As Object, e As EventArgs) Handles Timer1.Tick
If DateTime.Now > endTime Then
Timer1.Enabled = False
MessageBox.Show("You didn't finish in time.", "Sorry")
Me.Close()
Else
Seconds.Text = (DateTime.Now - endTime).ToString("hh\:mm\:ss")
End If
End Sub
This happens because your timer ticks at Minutes interval. If you want to show seconds in the label then your timer should tick within 1 second interval (maybe a few milliseconds etc.)
So instead of setting Timer1.Interval =details * 60000, set x = details * 60 and Timer1.Interval to 1000.
There is also variable scoping problem with your code. You have declared x as local variable inside Form1_Load, which means that it won't be available inside the Timer1_Tick. Move it outside the procedure.
Dim x As Integer
Public Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
Details = ds.Tables(0).Rows(0).Item("Time")
Timer1.Interval = 1000
x = Details * 60
Timer1.Enabled = True
End Sub
Private Sub Timer1_Tick(sender As Object, e As EventArgs) Handles Timer1.Tick
seconds.Text = x.ToString
If x = 0 Then
Timer1.Enabled = False
MessageBox.Show("You didn't finish in time.", "Sorry")
Me.Close()
Else
x-= 1
End If
End Sub
UPDATED
This is assuming that your database saved value is in Milliseconds. Otherwise modify appropriately.
Dim ticker As TimeSpan
Public Sub Form1_Load(ByVal sender As Object, ByVal e As EventArgs) Handles MyBase.Load
Details = ds.Tables(0).Rows(0).Item("Time")
Timer1.Interval = 1000
ticker = TimeSpan.FromMilliseconds(Details)
Timer1.Enabled = True
End Sub
Private Sub Timer1_Tick(ByVal sender As Object, ByVal e As EventArgs) Handles Timer1.Tick
seconds.Text = String.Format("{0:00}:{1:00}:{2:00}", ticker.Hours, ticker.Minutes, ticker.Seconds)
If ticker.Ticks <= 0 Then
Timer1.Enabled = False
MessageBox.Show("You didn't finish in time.", "Sorry")
Me.Close()
Else
ticker = ticker.Subtract(TimeSpan.FromSeconds(1))
End If
End Sub
This may not be completely what you may want, as I didn't convert the time or anything I just made it as basic as possiable and that way you should be able to work from it :)
Public Class Form1
Dim Time As Integer = 100 'Your time in seconds goes here!
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
lblTime.Text = Time
Timer1.Enabled = True
End Sub
Private Sub Timer1_Tick(sender As Object, e As EventArgs) Handles Timer1.Tick
Time = Time - 1
lblTime.Text = Time
If Time = 0 Then
Timer1.Enabled = False
MsgBox("You didn't finish in time.", "Sorry")
Me.Close()
End If
End Sub
End Class
Any problems just message me