How to stop the timer after specified time - vb.net

I have 3 texbox which will continuously running the random numbers.
May I know how to stop the timer after certain time?
Example
Timer1 stop after 5 seconds
Timer2 stop after 10 seconds
TImer2 stop after 15 seconds
Private Sub Timer1_Tick(sender As Object, e As EventArgs) Handles Timer1.Tick
Dim num1 As Integer
Dim rnd As New Random()
num1 = rnd.[Next](0, 2)
TextBox1.Text = Convert.ToString(num1)
End Sub
Private Sub Timer2_Tick(sender As Object, e As EventArgs) Handles Timer2.Tick
Dim num1 As Integer
Dim rnd As New Random
num1 = rnd.[Next](1, 9)
TextBox2.Text = Convert.ToString(num1)
End Sub
Private Sub Timer3_Tick(sender As Object, e As EventArgs) Handles Timer3.Tick
Dim num1 As Integer
Dim rnd As New Random
num1 = rnd.[Next](1, 9)
TextBox3.Text = Convert.ToString(num1)
End Sub
Private Sub btnrndpick_Click(sender As Object, e As EventArgs) Handles btnrndpick.Click
Timer1.Enabled = True
Timer2.Enabled = True
Timer3.Enabled = True
Timer4.Enabled = True
Timer5.Enabled = True
btnrndpick.Text = "RUNNING"
End Sub

Here is one way to do it with only 1 timer:
Private Rnd As New Random()
Private buttonPressTime As DateTime
Private Sub Timer1_Tick(sender As Object, e As EventArgs) Handles Timer1.Tick
If (DateTime.Now - buttonPressTime) < New TimeSpan(0, 0, 2) Then
SetTextBoxText(TextBox1, 0, 2)
End If
If (DateTime.Now - buttonPressTime) < New TimeSpan(0, 0, 5) Then
SetTextBoxText(TextBox2, 1, 9)
End If
If (DateTime.Now - buttonPressTime) < New TimeSpan(0, 0, 15) Then
SetTextBoxText(TextBox3, 1, 9)
Else
Timer1.Stop()
End If
End Sub
Private Sub SetTextBoxText(ByVal TextBox As TextBox, ByVal LowerBound As Integer, ByVal UpperBound As Integer)
TextBox.Text = Rnd.[Next](LowerBound, UpperBound).ToString()
End Sub
Private Sub btnrndpick_Click(sender As Object, e As EventArgs) Handles btnrndpick.Click
Timer1.Enabled = True
buttonPressTime = DateTime.Now
btnrndpick.Text = "RUNNING"
End Sub

Have you tried using an integer variable?
Something like
Dim number as integer = 0
Private Sub Timer1_Tick(sender As Object, e As EventArgs) Handles Timer1.Tick
number += 1
If number = 5 Then 'For example. But you need to adjust the tick property.
Timer1.Stop
End Sub

Related

How I can change the text of a single label from a string array vb.net?

so I want to display a string array in a single label that change the contents with a period of time ,
I ve tried every thing the timer, the background worker every thing , the problem when I use a loop inset a timer the interval in the start should be so long if the array items was so many so I tried the background worker but it not works
this is the code :
Dim array() As String = {"so", "nb", "de", "rty", "dcds"}
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
BackgroundWorker1.RunWorkerAsync()
End Sub
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
Control.CheckForIllegalCrossThreadCalls = False
End Sub
Private Sub BackgroundWorker1_DoWork(sender As Object, e As DoWorkEventArgs) Handles BackgroundWorker1.DoWork
Dim worker As BackgroundWorker = CType(sender, BackgroundWorker)
Dim delay As Integer = 2000
Dim interval As Integer = 100
Dim elapsed As Integer = 0
Dim pos As Integer = array.Length
While Not worker.CancellationPending
If (elapsed >= delay) Then
worker.ReportProgress(pos)
' change label text in the Progress event handler
pos = (pos + 1)
elapsed = 0
If (pos = array.Length) Then
Exit While
End If
End If
Thread.Sleep(interval)
End While
End Sub
Private Sub BackgroundWorker1_ProgressChanged(sender As Object, e As ProgressChangedEventArgs) Handles BackgroundWorker1.ProgressChanged
Dim j As Integer
For j = 0 To array.Length
Label1.Text = array(j)
Next
End Sub
Your for loop is overwriting the .Text property of the lable on each iteration. You will also get an Index Out of Range exception because the indexes of an array are zero based. The highest index will be 1 less than the .Length.
Private arStr() As String = {"so", "nb", "de", "rty", "dcds"}
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim LabelText = String.Join(Environment.NewLine, arStr)
Label1.Text = LabelText
End Sub
EDIT
Private arStr() As String = {"so", "nb", "de", "rty", "dcds"}
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Static index As Integer
If index < arStr.Length Then
Label1.Text &= arStr(index) & Environment.NewLine
index += 1
End If
End Sub
With asynchronous approach you can display array values one after another without BackgroundWorker and explicitly created Timer.
Private _values As New String() From {"so", "nb", "de", "rty", "dcds"}
Private Async Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
For Each value In _values
await Task.Delay(2000)
Next
End Sub
With asynchronous approach you can prevent button click before all values are displayed in the simple way as you would do in synchronous code.
Private Async Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim button = DirectCast(sender, Button);
button.Enabled = False
For Each value In _values
await Task.Delay(2000)
Next
button.Enabled = True
End Sub

I have this countdown timer and i want it to start from a number set in a variable

I have this count down timer and i want it to start to count down from a value given in a variable.
Public Class frmSinglePlayer
Private TargetDT As DateTime
Private CountDownFrom As TimeSpan = TimeSpan.FromMinutes(3)
Private Sub frmSinglePlayer_Load(sender As System.Object, e As System.EventArgs) Handles MyBase.Load
tmrCountdown.Interval = 500
TargetDT = DateTime.Now.Add(CountDownFrom)
tmrCountdown.Start()
End Sub
Private Sub tmrCountdown_Tick(sender As Object, e As System.EventArgs) Handles tmrCountdown.Tick
Dim ts As TimeSpan = TargetDT.Subtract(DateTime.Now)
If ts.TotalMilliseconds > 0 Then
lblTime.Text = ts.ToString("mm\:ss")
Else
lblTime.Text = "00:00"
tmrCountdown.Stop()
MessageBox.Show("Done")
End If
End Sub
End Class
I want to change instead of the number 3 in this line, to put the value from my variable.
Private CountDownFrom As TimeSpan = TimeSpan.FromMinutes(3)
I have 3 radiobuttons with different values.
Private Sub rd_1h_CheckedChanged(sender As Object, e As EventArgs) Handles rd_1h.CheckedChanged
ho = 1
End Sub
Private Sub rd_2h_CheckedChanged(sender As Object, e As EventArgs) Handles rd_2h.CheckedChanged
ho = 2
End Sub
Private Sub rd_3h_CheckedChanged(sender As Object, e As EventArgs) Handles rd_3h.CheckedChanged
ho = 3
End Sub
If is confusing , please ask me and sorry for my bad english.
Maybe you need something like this?
Private TargetDT As DateTime
Dim ho As Integer = 1
Private Sub StartTimerTick(sender As Object, e As System.EventArgs, Optional countDownFrom As Integer = 0)
If sender Is Nothing Then
TargetDT = DateTime.Now.Add(TimeSpan.FromMinutes(countDownFrom))
Dim mTmr = New Timer
mTmr.Interval = 500
AddHandler mTmr.Tick, AddressOf StartTimerTick
mTmr.Start()
Exit Sub
End If
Console.WriteLine("Tick ")
Dim ts As TimeSpan = TargetDT.Subtract(DateTime.Now)
If ts.TotalMilliseconds > 0 Then
lblTime.Text = ts.ToString("mm\:ss")
Else
lblTime.Text = "00:00"
CType(sender, Timer).Stop()
CType(sender, Timer).Dispose()
MessageBox.Show("Done")
End If
End Sub
Private Sub rd_1h_CheckedChanged(sender As Object, e As EventArgs) Handles rd_1h.CheckedChanged,
rd_2h.CheckedChanged,
rd_3h.CheckedChanged
Select Case CType(sender, Control).Name
Case "rd_1h"
ho = 1
Case "rd_2h"
ho = 2
Case "rd_3h"
ho = 3
End Select
'StartTimerTick(Nothing, Nothing, ho)
End Sub
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
StartTimerTick(Nothing, Nothing, ho)
End Sub

calculation is only performed once on food ordering form (VB)

I am making a food ordering form, and I am having trouble with the calculations. Every time a hotdog is ordered the form is supposed to add the cost to the total amount, so one hotdog is 2 dollars, add another and it says 4 dollars, etc. But it only performs the calculation once, so no matter how many items I add to the order the price stays the same, as if I had only ordered one.
I don't get any errors at runtime so it must be a logical error. Here is the full code. I don't know what other information I should give at this moment. All help is appreciated.
Public Class DroneDogs
Dim DogChoice As String
Dim condiment1 As String
Dim condiment2 As String
Dim condiment3 As String
Const DBL_TAX_RATE As Double = 0.07
Const DBL_DRONE_DOG As Double = 1.99
Dim intNumDog As Integer
Dim dblSubTotal As Double
Dim dblSalesTax As Double
Dim dblTotalCost As Double
Private Sub btnAddCustomer_Click(sender As Object, e As EventArgs) Handles btnAddCustomer.Click
cboCurrentCustomers.Items.Add(txtAddCustomer.Text)
End Sub
Private Sub optBeef_CheckedChanged(sender As Object, e As EventArgs) Handles optBeef.CheckedChanged
If (optBeef.Checked) Then
DogChoice = "Beef Dog"
End If
End Sub
Private Sub optPork_CheckedChanged(sender As Object, e As EventArgs) Handles optPork.CheckedChanged
If (optPork.Checked) Then
DogChoice = "Pork Dog"
End If
End Sub
Private Sub optTurkey_CheckedChanged(sender As Object, e As EventArgs) Handles optTurkey.CheckedChanged
If (optTurkey.Checked) Then
DogChoice = "Turkey Dog"
End If
End Sub
Private Sub chkKetchup_CheckedChanged(sender As Object, e As EventArgs) Handles chkKetchup.CheckedChanged
If (chkKetchup.Checked) Then
condiment1 = " + Ketchup"
Else
condiment1 = Nothing
End If
End Sub
Private Sub chkMustard_CheckedChanged(sender As Object, e As EventArgs) Handles chkMustard.CheckedChanged
If (chkMustard.Checked) Then
condiment2 = " + Mustard"
Else
condiment2 = Nothing
End If
End Sub
Private Sub chkRelish_CheckedChanged(sender As Object, e As EventArgs) Handles chkRelish.CheckedChanged
If (chkRelish.Checked) Then
condiment3 = " + Relish"
Else
condiment3 = Nothing
End If
End Sub
Private Sub btnAddDog_Click(sender As Object, e As EventArgs) Handles btnAddDog.Click
intNumDog = +1
dblSubTotal = intNumDog * DBL_DRONE_DOG
dblSalesTax = dblSubTotal * DBL_TAX_RATE
dblTotalCost = dblSubTotal + dblSalesTax
txtSub.Text = dblSubTotal.ToString("c2")
txtTax.Text = dblSalesTax.ToString("c2")
txtTotal.Text = dblTotalCost.ToString("c2")
Dim addCondiment As String = condiment1 + condiment2 + condiment3
If (DogChoice = "Beef Dog") Or
(DogChoice = "Pork Dog") Or
(DogChoice = "Turkey Dog") Then
lstOrder.Items.Add(DogChoice + addCondiment + ": " + txtTotal.Text)
Else
MsgBox("Please select a Hot Dog type.")
End If
End Sub
Private Sub btnClearOrder_Click(sender As Object, e As EventArgs) Handles btnClearOrder.Click
lstOrder.Items.Clear()
txtSub.Clear()
txtTax.Clear()
txtTotal.Clear()
chkKetchup.Checked = 0
chkMustard.Checked = 0
chkRelish.Checked = 0
optBeef.Checked = 0
optPork.Checked = 0
optTurkey.Checked = 0
End Sub
Private Sub btnExit_Click(sender As Object, e As EventArgs) Handles btnExit.Click
'Exits the program
If MessageBox.Show("Do you want to exit the DroneDogs application?", "DroneDogs",
MessageBoxButtons.YesNo, MessageBoxIcon.Question) _
= DialogResult.Yes Then
Application.Exit()
End If
End Sub
Private Sub btnOrderComplete_Click(sender As Object, e As EventArgs) Handles btnOrderComplete.Click
Receipt.Show()
End Sub
Private Sub btnRemoveDog_Click(sender As Object, e As EventArgs) Handles btnRemoveDog.Click
lstOrder.Items.Remove(lstOrder.SelectedItem)
End Sub
End Class
I think the problem is with the line
intNumDog = +1
In this line, you always set intNumDog to the value of +1. This is the same as:
intNumDog = 1
You want to add one to the value of intNumDog:
intNumDog += 1

Rotating line with pythagoras formula

I want to rotate a line but i don't want to use radians or pi.I created an algorithm (if i can call it like that).I use pythagoras formula with two functions and two timers to rotate the line ,but i think there's an error because it rotate faster after 180 degrees rotation.Why?Here's my code:
Public Class Form1
Private Structure poi
Dim x As Integer
Dim y As Integer
End Structure
Dim x1 As Integer, y1 As Integer
Dim x As Integer, y As Integer
Dim val As Integer
Dim obxy As poi
Dim moupos As poi
Private Sub Timer1_Tick(sender As Object, e As EventArgs) Handles Timer1.Tick
Call calcxy(val, 100)
x = obxy.x
y = obxy.y
val = val - 1
Refresh()
If -val > 100 Then
Timer1.Enabled = False
Timer2.Enabled = True
End If
End Sub
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
If Button1.Text = "Start" Then
Timer1.Enabled = True
Button1.Text = "Stop"
Else
Timer1.Enabled = False
Timer2.Enabled = False
Button1.Text = "Start"
End If
End Sub
Sub calcxy(choice As Integer, radius As Integer)
Dim yval As Integer
yval = Math.Sqrt(radius ^ 2 - choice ^ 2)
obxy.x = moupos.x - choice
obxy.y = moupos.y - yval
End Sub
Sub recalcxy(choice As Integer, radius As Integer)
Dim yval As Integer
yval = Math.Sqrt(radius ^ 2 - choice ^ 2)
obxy.x = moupos.x - choice
obxy.y = moupos.y + yval
End Sub
Private Sub Form1_MouseClick(sender As Object, e As MouseEventArgs) Handles Me.MouseClick
moupos.x = e.X
moupos.y = e.Y
End Sub
Private Sub Form1_Paint(sender As System.Object, e As System.Windows.Forms.PaintEventArgs) Handles MyBase.Paint
Dim pen As New System.Drawing.Pen(System.Drawing.Color.Black, 1)
e.Graphics.DrawLine(pen, moupos.x, moupos.y, x, y)
End Sub
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
val = 100
End Sub
Private Sub Timer2_Tick(sender As Object, e As EventArgs) Handles Timer2.Tick
val = val + 1
Call recalcxy(val, 100)
x = obxy.x
y = obxy.y
Refresh()
If val + 1 > 100 Then
Timer2.Enabled = False
Timer1.Enabled = True
End If
End Sub
End Class

VB.net real-time time elapsed feature

I already have created a real time clock that synchronizes with the computer time and is being displayed in a label.
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
Timer1.Enabled = True
End Sub
Private Sub Timer1_Tick(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Timer1.Tick
Time.Text = Date.Now.ToString("h:mm:ss tt")
End Sub
I want to make a real-time time elapsed feature that keeps on counting the seconds/minutes/hours elapsed from the time it started till the time it stops and it would be basing on the real-time clock i have created. I would be creating a start and stop button for this. Is this possible? Thanks in advance.
I am now able to complete everything and i added a feature that records the starting and ending time based on my real time clock. Here is my working code:
Dim hr, min, sec As Integer
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
Timer1.Enabled = True
End Sub
Private Sub Timer1_Tick(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Timer1.Tick
Time.Text = Date.Now.ToString("h:mm:ss tt")
End Sub
Private Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click
Start.Text = ""
EndLbl.Text = ""
Elapse.Text = ""
Timer2.Enabled = True
Start.Text = Time.Text
End Sub
Private Sub Timer2_Tick(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Timer2.Tick
sec = sec + 1
If (sec = 60) Then
sec = 0
min = min + 1
ElseIf (min = 60) Then
min = 0
hr = hr + 1
ElseIf (hr = 24) Then
hr = 0
min = 0
sec = 0
End If
Elapse.Text = String.Format("{0}hr : {1}min : {2}sec", hr, min, sec)
Timer2.Interval = 1000
End Sub
Private Sub Button3_Click(sender As Object, e As EventArgs) Handles Button3.Click
Timer2.Enabled = False
EndLbl.Text = Label4.Text
hr = 0
min = 0
sec = 0
Timer2.Interval = 1
End Sub
Credits to the starting code given by NeverHopeless. Thanks alot.
I suggest you use only 1 timer:
Public Class Form2
Private _elapseTimerRunning As Boolean = False
Private _elapseStartTime As DateTime
Private Sub Form2_Load(sender As Object, e As EventArgs) Handles Me.Load
Timer1.Interval = 1000
Timer1.Enabled = True
End Sub
Private Sub Timer1_Tick(sender As Object, e As EventArgs) Handles Timer1.Tick
txtTime.Text = Now.ToString("h:mm:ss tt")
If _elapseTimerRunning = True Then
Dim elapsedtime = DateTime.Now.Subtract(_elapseStartTime)
txtElapsed.Text = String.Format("{0}hr : {1}min : {2}sec", elapsedtime.Hours, elapsedtime.Minutes, elapsedtime.Seconds)
End If
End Sub
Private Sub btnStart_Click(sender As Object, e As EventArgs) Handles btnStart.Click
_elapseStartTime = DateTime.Now
_elapseTimerRunning = True
End Sub
Private Sub btnStop_Click(sender As Object, e As EventArgs) Handles btnStop.Click
_elapseTimerRunning = False
End Sub
End Class
An example for displaying the elapsed time the application has run.
Public Class Form1
'shows elapsed time that the app has run
'
Dim elapTimer As New Threading.Timer(AddressOf tick, Nothing, 1000, 1000)
Dim stpw As Stopwatch = Stopwatch.StartNew
Private Sub tick(state As Object)
If stpw.IsRunning Then
'format - http://msdn.microsoft.com/en-us/library/ee372287.aspx
Me.Invoke(Sub()
Label1.Text = stpw.Elapsed.ToString("d\ \ hh\:mm\:ss\.ff")
End Sub)
End If
End Sub
End Class
To add start/stop functionality using buttons:
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
'start the elapsed timer
stpw.Start() 'continue
'or
'stpw.Restart() 'restart
End Sub
Private Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click
stpw.Stop()
End Sub
Something like this would help you: (untested, but will give you a starter)
Dim hr, min, sec As Integer 'msec;
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
Timer1.Enabled = True
Timer2.Enabled = True
End Sub
Private Sub Timer2_Tick(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Timer1.Tick
'msec++;
'if(msec == 60) { msec = 0; sec++; }
sec+=1;
if(sec = 60) Then
sec = 0 : min+=1
end if
if(min = 60) Then
min = 0 : hr+=1
end if
if(hr = 24) Then
hr = 0 : min = 0 : sec = 0
end if
'TimeElapsed.Text = String.Format("{0}:{1}:{2} {3}", hr, min, sec, msec)
TimeElapsed.Text = String.Format("{0}:{1}:{2}", hr, min, sec)
End Sub
Private Sub Timer1_Tick(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Timer1.Tick
Time.Text = Date.Now.ToString("h:mm:ss tt")
End Sub
NOTE: Timer2 will run for every second.