StopWatch and Timer Accuracy - vb.net

I'm using the following code to control a label to output a stopwatch. The buttons work, and the label is outputting the information mostly correctly, however it only update every so often and i would like for the label to update the information every millisecond.
Private SW As New Stopwatch
Dim timercount As Integer = 1 'The number of seconds
Private Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click
SW.Start()
Timer1.Start()
End Sub
Private Sub Button3_Click(sender As Object, e As EventArgs) Handles Button3.Click
Timer1.Enabled = False 'Stop the timer
timercount = 0 'Reset to 0 seconds
Label10.Text = "00:00:00.000"
End Sub
Private Sub Timer1_Tick(sender As Object, e As EventArgs) Handles Timer1.Tick
Dim ts As TimeSpan = SW.Elapsed
Label10.Text = ts.ToString("hh\:mm\:ss\.fff")
End Sub
Private Sub Button4_Click(sender As Object, e As EventArgs) Handles Button4.Click
Timer1.enabled = False
End Sub
Any help is much appreciated.

You can set the timer to a reasonable value, say 20 times a second, to rapidly display it changing.
You can create the timer and stopwatch in code, which I think is easier than adding a control to the form—you can see right there in the code what is being programmed. I used sensible names for the buttons so that you can tell what is meant to do what.
If you keep the sub to display the data separate from the code that processes the data, it is easy to change the display in just one place, in case someone decided they wanted it written as words, for example, or maybe the hours in a separate box, or something.
Public Class Form1
Dim sw As New Stopwatch
Dim tim As Timer
Private Sub ShowElapsedTime()
lblTime.Text = sw.Elapsed.ToString("hh\:mm\:ss\.fff")
End Sub
Private Sub bnStart_Click(sender As Object, e As EventArgs) Handles bnStart.Click
sw.Restart()
tim.Enabled = True
End Sub
Private Sub bnStop_Click(sender As Object, e As EventArgs) Handles bnStop.Click
sw.Stop()
tim.Enabled = False
ShowElapsedTime()
End Sub
Private Sub bnReset_Click(sender As Object, e As EventArgs) Handles bnReset.Click
tim.Enabled = False
sw.Reset()
ShowElapsedTime()
End Sub
Private Sub tim_Tick(sender As Object, e As EventArgs)
ShowElapsedTime()
End Sub
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
tim = New Timer With {.Interval = 50}
AddHandler tim.Tick, AddressOf tim_Tick
ShowElapsedTime()
End Sub
End Class

Related

Auto refresh form every 30 seconds vb.net

I want to have a form opened all day but I want to auto refresh it every 30 seconds.
I am using this code:
Private Sub tempo(sender As System.Object, e As System.EventArgs) Handles MyBase.Load
Dim timer = New Timer
timer.Interval = 30 * 1000
AddHandler timer.Tick, AddressOf Form12_Load
timer.Start()
End Sub
Private Sub Form12_Load(sender As Object, e As EventArgs) Handles MyBase.Load
...
End sub
But it isn't working. Do you know what I am doing wrong?
Thank you.
My 0.02, should not need much explanation:
Private WithEvents clock As New Timers.Timer
Private Sub Form12_Load(sender As Object, e As EventArgs) Handles MyBase.Load
With clock
.Interval = 30000
.AutoReset = True
.Enabled = True
.Start()
End With
End Sub
Private Sub clock_tick() Handles clock.Elapsed
Me.BeginInvoke(Sub()
Me.Refresh()
End Sub)
End Sub
Firsly you need to take timer. after that you select time interval. how much time you want to refresh from load page. in my case im creating one function form load in side formload function is nothing you just type your commands. want to update on load page ===**
MyBase.Update()** im using that.
'Private Sub Timer3_Tick(sender As Object, e As EventArgs) Handles Timer3.Tick
' formload()
' ref_screen()
'End Sub
Hi you have to call the form_load event from the tick-timer event:
Private Sub Form12_Load(sender As Object, e As EventArgs) Handles MyBase.Load
Dim timer = New Timer
timer.Interval = 30 * 1000
AddHandler timer.Tick, AddressOf timer_Tick
timer.Start()
End sub
Private Sub timer_Tick(ByVal sender As Object, ByVal e As EventArgs)
Form12_Load(me,nothing)
End Sub

Change the color of a button(s) for a duration of time

I have a small VB.net app that has a LOT of buttons. I need to change the back color of the buttons when they are clicked and then set it back to its original color after a duration of 10 seconds. I am struggling with either using a timer or the time process both of which have their own issues.
Any ideas to make this work and work efficiently?
Code:
Private Sub MyButtons_Click(sender As Object, e As EventArgs) _
Handles Button1.Click,
Button2.Click
Dim myButton = DirectCast(sender, Button)
MakeCall()
myButton.BackColor = Color.Green
'TurnOnActiveCallCOLOR.Enabled = True
For i As Integer = 0 To 10000 - 1
Threading.Thread.Sleep(10000)
Next
myButton.BackColor = Color.FromArgb(64, 64, 64)
End Sub
Here is an example of using a Windows Forms Timer to accomplish what you need:
Private MyButton As Button
Private Sub MyButtons_Click(sender As Object, e As EventArgs) Handles Button1.Click, Button2.Click
MyButton = DirectCast(sender, Button)
MyButton.BackColor = Color.Green
Timer1.Enabled = True
MakeCall()
End Sub
Private Sub Timer1_Tick(sender As Object, e As EventArgs) Handles Timer1.Tick
MyButton.BackColor = Color.FromArgb(64, 64, 64)
Timer1.Enabled = False
End Sub
To handle an arbitrary number of buttons, you could have something like this:
Public Class Form1
Dim buttonTimers As New Dictionary(Of Control, ButtonTimer)
Class ButtonTimer
Property Timeout As Integer = 2000
Property Target As Control
Property ActiveColor As Color = Color.Green
Property DefaultColor As Color = Color.FromArgb(64, 64, 64)
Private tim As Timer
Sub TimTick(sender As Object, e As EventArgs)
tim.Stop()
Target.BackColor = DefaultColor
End Sub
Sub New()
' empty constructor
End Sub
Sub New(target As Control)
Me.Target = target
Me.Target.BackColor = Me.ActiveColor
tim = New Timer With {.Interval = Timeout}
AddHandler tim.Tick, AddressOf TimTick
tim.Start()
End Sub
Sub Restart()
Target.BackColor = Me.ActiveColor
If tim IsNot Nothing Then
tim.Stop()
tim.Start()
End If
End Sub
Public Sub DisposeOfTimer()
If tim IsNot Nothing Then
tim.Stop()
RemoveHandler tim.Tick, AddressOf TimTick
tim.Dispose()
End If
End Sub
End Class
Private Sub Button_Click(sender As Object, e As EventArgs) Handles Button1.Click, Button2.Click
Dim myButton = DirectCast(sender, Button)
'MakeCall()
If buttonTimers.ContainsKey(myButton) Then
buttonTimers(myButton).Restart()
Else
buttonTimers.Add(myButton, New ButtonTimer(myButton))
End If
End Sub
Private Sub Form1_FormClosing(sender As Object, e As FormClosingEventArgs) Handles MyBase.FormClosing
For Each x In buttonTimers
x.Value.DisposeOfTimer()
Next
End Sub
End Class
If a button is clicked again before the timeout, the time is restarted.
You can add other constructors if you want to have a different timeout/colours for different buttons.
The MyBase.FormClosing code should be included in your form closing handler (if there is one) so that the timers are cleaned up properly.
I expect it would be tidier overall to make your own custom button class which inherits from Button, so you might want to investigate doing that. (How to: Inherit from Existing Windows Forms Controls.)
asynh and await if you don't want use timer. Simple method using task.delay
Private Async Sub ButtonClick(sender As Object, e As EventArgs) Handles Button1.Click, Button2.Click, Button3.Click, Button4.Click
DirectCast(sender, Button).BackColor = Color.Red 'after click setcolor to red
Await setColorAfterDelay(sender) 'Add this comand on button click and don't forget add asynh before sub in this method
End Sub
Public Async Function setColorAfterDelay(sender As Object) As Task
Await Task.Delay(1000) ''Milisecound how long you wana dealey
DirectCast(sender, Button).BackColor = Color.White 'and set colorto white
End Function
With the use of lambda expressions (and a lookup table if you want to interact with it further) you can do this pretty easily:
'Lookup table for if you want to be able to interact with the timers even more.
Dim ButtonTimers As New Dictionary(Of Button, Timer)
Private Sub MyButtons_Click(sender As Object, e As EventArgs) _
Handles Button1.Click, Button2.Click
MakeCall()
Dim myButton = DirectCast(sender, Button)
myButton.BackColor = Color.Green
'If a timer already exists for the button, restart it.
Dim existingTimer As Timer = Nothing
If ButtonTimers.TryGetValue(myButton, existingTimer) Then
existingTimer.Stop()
existingTimer.Start()
Return 'Do not execute the rest of the code.
End If
'Create the timer and set its Interval to 10000 ms (10 seconds).
Dim buttonTimer As New Timer() With {.Interval = 10000}
'Add a handler to its Tick event.
AddHandler buttonTimer.Tick, _
Sub(tsender As Object, te As EventArgs)
myButton.BackColor = Color.FromArgb(64, 64, 64)
'Dispose timer and remove from lookup table.
ButtonTimers.Remove(myButton)
buttonTimer.Stop()
buttonTimer.Dispose()
End Sub
ButtonTimers.Add(myButton, buttonTimer)
buttonTimer.Start()
End Sub
If you want to interact with a button's timer (if one exists) you can do:
Dim buttonTimer As Timer = Nothing
If ButtonTimers.TryGetValue(yourButtonHere) Then
'Do something with buttonTimer...
End If
This could probably be done better by dynamically creating timer controls so each button has it's own timer but here is what I came up with.
Oh, an set your timer to 1000 interval and enabled to 'False'.
Public Class Form1
Dim T1 As Integer = 0
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
End Sub
Private Sub Timer1_Tick(sender As Object, e As EventArgs) Handles Timer1.Tick
T1 = T1 + 1
If T1 = 10 Then
For Each button In Controls
button.backcolor = Color.FromArgb(225, 225, 225)
Next
Timer1.Stop()
T1 = 0
End If
Me.Text = T1
End Sub
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Button1.BackColor = Color.Red
Timer1.Start()
End Sub
Private Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click
Button2.BackColor = Color.Orange
Timer1.Start()
End Sub
Private Sub Button3_Click(sender As Object, e As EventArgs) Handles Button3.Click
Button3.BackColor = Color.Yellow
Timer1.Start()
End Sub
Private Sub Button4_Click(sender As Object, e As EventArgs) Handles Button4.Click
Button4.BackColor = Color.Green
Timer1.Start()
End Sub
Private Sub Button5_Click(sender As Object, e As EventArgs) Handles Button5.Click
Button5.BackColor = Color.Blue
Timer1.Start()
End Sub
End Class

Late Binding Issue with BackgroundWorker in VB.Net

I am running a BackgroundWorker, and want to report its progress. In the example below I create a test list which the BackgroundWorker then iterates through. The problem lies in the line 'sender.ReportProgress(i)'. If I have Option Strict on, it does not like my use of 'i' due to Late Binding issues. Is there any alternative way to code this and avoid that issue?
Public Class Form1
Private Sub Form1_Load(sender As System.Object, e As System.EventArgs) Handles MyBase.Load
' Configuring for Background Workers
Control.CheckForIllegalCrossThreadCalls = False
Dim MyList As New List(Of String)
For a As Integer = 0 To 100
MyList.Add(CStr(a))
Next
End Sub
Private Sub Button1_Click(sender As System.Object, e As System.EventArgs) Handles Button1.Click
Dim bgw As New System.ComponentModel.BackgroundWorker
bgw.WorkerReportsProgress = True
bgw.WorkerSupportsCancellation = True
AddHandler bgw.DoWork, AddressOf bgw_DoWork
' I create a BackgroundWorker here rather than add one in the toolbox so that I can specify the Handler and use different Handler routines for different part of a large program.
Button1.Enabled = False
Dim progress As New Progress(bgw)
progress.ShowDialog()
Button1.Enabled = True
End Sub
Private Sub bgw_DoWork(sender As System.Object, e As System.ComponentModel.DoWorkEventArgs)
For i = 0 To MyList.Count -1
Label1.Text = MyList(i)
sender.ReportProgress(i)
System.Threading.Thread.Sleep(200)
Label1.Refresh()
Next
End Sub
End Class
Public Class Progress
Private WithEvents _BGW As System.ComponentModel.BackgroundWorker
Public Sub New(ByVal BGW As System.ComponentModel.BackgroundWorker)
_BGW = BGW
InitializeComponent()
End Sub
Private Sub frmProgress_Shown(sender As Object, e As System.EventArgs) Handles Me.Shown
If Not IsNothing(_BGW) Then
_BGW.RunWorkerAsync()
End If
End Sub
Private Sub _BGW_ProgressChanged(sender As Object, e As System.ComponentModel.ProgressChangedEventArgs) Handles _BGW.ProgressChanged
ProgressBar1.Value = e.ProgressPercentage
Label1.Text = e.ProgressPercentage
End Sub
Private Sub _BGW_RunWorkerCompleted(sender As Object, e As System.ComponentModel.RunWorkerCompletedEventArgs) Handles _BGW.RunWorkerCompleted
Me.Close()
End Sub
End Class
CType(sender, BackgroundWorker).ReportProgress(i)
Also, if you want to do multiple actions with it, then create a local reference variable like this:
Private Sub bgw_DoWork(sender As System.Object, e As System.ComponentModel.DoWorkEventArgs)
Dim bgw As System.ComponentModel.BackgroundWorker = DirectCast(sender, System.ComponentModel.BackgroundWorker)
' ... now you can use "bgw" multiple times below instead of casting each time ...
For i = 0 To MyList.Count -1
Label1.Text = MyList(i)
bgw.ReportProgress(i)
bgw.SomethingElse()
bgw.MoreStuff()
System.Threading.Thread.Sleep(200)
Label1.Refresh()
Next
End Sub
Obviously this isn't necessary in your case, just an FYI...

Interrupting loop in VB.net

I have a loop that runs but would like it to stop on the press of a button and start again when another is pressed. This is my code:
Public Class Form1
Private loopon As Boolean
Public Function ping(ByVal server As String) As String
Dim s As New Stopwatch
s.Start()
My.Computer.Network.Ping(server)
s.Stop()
Return s.ElapsedMilliseconds.ToString
End Function
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
loopon = True
TextBox1.Text = "Ping results:"
Do While loopon = True
TextBox1.AppendText(Environment.NewLine)
TextBox1.AppendText(ping("server name here"))
Loop
End Sub
Private Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click
loopon = False
End Sub
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
TextBox1.Text = String.Empty
TextBox1.Text = "Ping results:"
loopon = True
End Sub
End Class
When I try to run the code, with debugging, my computer gives me a blue screen after a while and restarts. I'm pretty sure I messed up with the exiting of the loop. Any suggestions?
You could use a Timer to ping (say) every 5 seconds until the "Stop" button is clicked. In the Form Designer, drag a Timer onto the form, and use this code:
Public Class Form1
Private stopPing As Boolean
Public Sub Ping(ByVal server As String)
Dim s As New Stopwatch
s.Start()
My.Computer.Network.Ping(server)
s.Stop()
TextBox1.AppendText(Environment.NewLine & s.ElapsedMilliseconds.ToString)
End Sub
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
TextBox1.Text = "Ping results:"
Ping "server name here"
Timer1.Interval = 5000 'Set timer Interval to 5 seconds
Timer1.Start
End Sub
Private Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click
stopPing = True
End Sub
Sub Timer1_Tick(sender As Object, e As EventArgs) Handles Timer1.Tick
If stopPing Then Timer1.Stop Else Ping "server name here"
End Sub
End Class

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