Create a simple timer to count seconds, minutes and hours - vb.net

I'm trying to create a pretty simple program that basically is a timer.
I have three sets of labels, lbl_seconds, lbl_minutes and lbl_hours.
These labels have the default value of 00:00 and I want the timer to change that for each label. I have googled this but I cannot seem to find any good info on it.
Do I need three separate timers? I have also noticed that the timers have their own tick event handler. I guess it's in this that I need to change the value of the label. How to do just that?

Here is an example of this
Dim timercount As Integer = 60 'The number of seconds
Private Sub btnStart_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnStart.Click
Timer1.Interval = 1000 'The number of miliseconds in a second
Timer1.Enabled = True 'Start the timer
End Sub
Private Sub btnReset_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnReset.Click
Timer1.Enabled = False 'Stop the timer
timercount = 60 'Reset to 60 seconds
lblOutput.Text = timercount.ToString() 'Reset the output display to 60
End Sub
Private Sub Timer1_Tick(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Timer1.Tick
lblOutput.Text = timercount.ToString() 'show the countdown in the label
If timercount = 0 Then 'Check to see if it has reached 0, if yes then stop timer and display done
Timer1.Enabled = False
lblOutput.Text = "Done"
Else 'If timercount is higher then 0 then subtract one from it
timercount -= 1
End If
End Sub

I think you need something of this sort
Public Function GetTime(Time as Integer) As String
Dim Hrs As Integer 'number of hours '
Dim Min As Integer 'number of Minutes '
Dim Sec As Integer 'number of Sec '
'Seconds'
Sec = Time Mod 60
'Minutes'
Min = ((Time - Sec) / 60) Mod 60
'Hours'
Hrs = ((Time - (Sec + (Min * 60))) / 3600) Mod 60
Return Format(Hrs, "00") & ":" & Format(Min, "00") & ":" & Format(Sec, "00")
End Function
You pass the time (in seconds) you'd like to display on the label's text and the time will be formatted as you like it.
e.g.
lblTime.Text = GetTime(90)
This will display 00:01:30 on the label.
For reference, you can see this project I submitted on FreeVBCode some time ago. The only caveat is the project is in VB6. You should be able to open it in Visual Studio though.

Start off by adding a timer. Call it whatever you like, in this example I will be keeping it as Timer1. Add a label and set the text as: 00:00.
In the code after the class has been set (usually it is Public Class Form1) make a variable as a stopwatch: Dim stopwatch As New Stopwatch
In the timer tick event code, put the following: (Please note that my 00:00 label is called Label1)
Label1.Text = String.Format("{0}:{1}:{2}", watch.Elapsed.Hours.ToString("00"), watch.Elapsed.Minutes.ToString("00"), watch.Elapsed.Seconds.ToString("00"))

Use one timer and in event sub change value of your labels.
You need one timer and three counter for seconds, minutes and hours.
Count minutes, then modulo minutes / 60, if return 0 then start count minutes.
Modulo minutes/60, if return 0 then start count hours.

Related

VB.Net Countdown - Timer has delay

So I just created a Countdown which updates each timer tick but using a real countdown to compare the one I coded has a small delay. After 1 Minute its like 3 Seconds slower than a normal timer.
The weird thing is that it works fine if I set the Interval to something above 1000 = update each second.
But everything below 1000 has a delay and I want a timer with milliseconds, update each 0.1 secon = Interval 100.
Thats the code I have so far (It looks messy because it switches the color of the label once it reaches a certain amount of time left)
Private Sub Timer1_Tick(sender As Object, e As EventArgs) Handles Timer1.Tick
Label1.Text = "Time left" & count
If count >= 12 Then
If change = False Then
Label1.ForeColor = Color.Chartreuse
change = True
End If
Timer1.Interval = 2000
count = count - 2
ElseIf count <= 11.5 And count >= 7.5 Then
If playaudio = False Then
playaudio = True
Label1.ForeColor = Color.Yellow
End If
Timer1.Interval = 100
count = count - 0.1
ElseIf count <= 7.5 And count >= 0 Then
count = count - 0.1
If changes = False Then
Label1.ForeColor = Color.Red
changes = True
End If
ElseIf count <= 0 Then
Timer1.Stop()
Timer2.Enabled = True
Timer2.Start()
playaudio = False
changes = False
change = False
count = 100
End If
End Sub
Is there any ohter way that the timer doesnt delay?
I think it's because the actions you take are delaying the next timer.
One way to work around the problem would be to set the timer to something like 10ms. At each tick, you check if the previous refresh is older than the desired delay.
Or you can set the timer in another thread, which will not be affected by the execution time.
Forms timers are notoriously inaccurate. Use a stopwatch to measure time and the Timer to update the display.
Public Class Form1
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
Stpw.Start()
Timer1.Start() 'I have it set to 100ms.
End Sub
Private CountDown As TimeSpan = TimeSpan.FromSeconds(10.0#)
Private Stpw As New Stopwatch
Private Sub Timer1_Tick(sender As Object, e As EventArgs) Handles Timer1.Tick
If Stpw.Elapsed >= CountDown Then
Timer1.Stop()
Stpw.Stop()
Label1.Text = "Blast Off"
Else
Dim ToGo As TimeSpan = CountDown - Stpw.Elapsed
Label1.Text = ToGo.ToString("hh\:mm\:ss\.f")
Select Case ToGo.TotalSeconds
End Select
End If
End Sub
End Class
Start with this and you'll see how it works. Your color coding can probably go in the Select.
Here's a bit of a restructuring of your code. It's like dbasnett's stopwatch, except it uses a class you're more likely to be familiar with, to introduce the concept that "instead of using a timer and measuring time passage by adding up (or taking away) every time it ticks (which is subject to cumulative errors), pick a moment in time and regularly calculate how far away it is":
'code that starts a minute countdown
'class level property noting the end time
Private _endDateTime as DateTime
'the end time is a minute away
_endDateTime = DateTime.UtcNow.AddMinutes(1)
'we only need one timer
timer1.Start()
Private Sub Timer1_Tick(sender As Object, e As EventArgs) Handles Timer1.Tick
Dim count = (_endDateTime - DateTime.UtcNow).TotalSeconds 'how far away is the end time?
Label1.Text = $"Time left {count:0.0}s"
If count <= 0 Then 'reset
Timer1.Stop()
Label1.ForeColor = Color.Chartreuse
playaudio = False
Else If count <= 7.5 Then
Label1.ForeColor = Color.Red
ElseIf count <= 11.5 Then
playaudio = True
Label1.ForeColor = Color.Yellow
End If
End Sub
There is a lot of redundancy that can be removed in your code; we'll use a single timer, it can tick on whatever interval you like; if there is a label that is counting down with 0.1 second precision then we should maybe make it tick every 50ms
If you swap your ifs around you won't need to make them a range; if you're measuring less than, put the test for the smallest number first. Mostly these ifs won't enter at all, then when there is less than 11.5 seconds to go, the last if will start activating etc..
Nothing happens if you set a label color to be the same as it already is so you don't need that complicated Boolean setup with change/changes to make sure you only set the color once
The crucial thing is we have a fixed end point in time and every time we tick we work out how far away that is. We could tick 1000 times a second or once every 10 seconds, it doesn't matter; the end time is the end time is the end time

VLC ActiveX seek bar help in vb.net

I am making a video player, using VLC ActiveX called AxVLCPlugin21, so want to make it real as possible. So i thought of putting a Trackbar1 to seek through a video, with a Label1 for the time in 0:0/0:0 format
What I know:
Private Sub Timer1_Tick(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Timer1.Tick
' When the timer runs the, label text will be set to the return value of the function formattime()
With TrackBar1
.Minimum = 0
.Maximum = AxVLCPlugin21.input.Length
End With
Label1.Text = formatTime(AxVLCPlugin21.input.Time) & "/" & formatTime(AxVLCPlugin21.input.Length)
Try
TrackBar1.Value = AxVLCPlugin21.input.time
Catch ex As Exception
End Try
End Sub
Private Sub TrackBar1_Scroll(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles TrackBar1.Scroll
AxVLCPlugin21.input.Time = TrackBar1.Value
AxVLCPlugin21.playlist.play()
End Sub
Function formatTime(ByVal timeVal As Integer)
Dim timeHour As Integer
Dim timeSec As Integer
Dim timeMin As Integer
timeHour = Math.Round(timeVal \ 1000)
timeSec = timeHour Mod 60
If timeSec < 10 Then
timeSec = "0" & timeSec
timeHour = (timeHour - timeSec) \ 60
timeMin = timeHour Mod 60
End If
If timeMin < 10 Then
timeMin = "0" & timeMin
timeHour = (timeHour - timeMin) \ 60
End If
If timeHour < 0 Then
Return timeHour & ":" & timeMin & ":" & timeSec
Else
Return timeMin & ":" & timeSec
End If
End Function
Code cited from here
The seek bar works perfectly but the label containing the time does not, for example if the video a 5 minute and when playing the video, the time is in the 50th second the label will show 0.50/5.0, when the video time is 2 minutes and 55 seconds it will show 0.55/5.0.
My point is that when the video time reaches more than 60 seconds the minute resets to zero.
Is there a problem in the code? I have included some extra information like the Trackbar1_Scroll and Timer1_Tick.
And also I want the time to appear like 00:00/00.00 and the function does not have the code for hours so anyone can help me creating an hour in the function, and display the time as 00:00:00/00:00:00
Thank you
[shannon]

How to make button press limit time in vb.net

I want a code when I pressing the button Then the button is Impossible to click
again for 24 hours and after the 24 the button available again.
For example:
When button is clicked disable button and start a timer (timer should have 24h interval) when it ticks, enable button and stop the timer.
As already mentioned in the above comments, there are many ways to do this depending on your need. Below is just a simple example that should help.
Private ButtonTimer As New Timer
Private ButtonCountDown As Integer
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
'Disable Button
Button1.Enabled = False
'Set Countdown
ButtonCountDown = 24
'Setup Timer
AddHandler ButtonTimer.Tick, AddressOf ButtonTimer_Tick
ButtonTimer.Interval = 1000 * 60 * 60 'Every 1 Hour
ButtonTimer.Start()
End Sub
Private Sub ButtonTimer_Tick(ByVal obj As Object, ByVal e As EventArgs)
'Decrement ButtonCountDown and if not zero we can just leave and do nothing.
ButtonCountDown -= 1
If Not ButtonCountDown = 0 Then Exit Sub
'We have reached zero, stop timer and clean up.
ButtonTimer.Stop()
RemoveHandler ButtonTimer.Tick, AddressOf ButtonTimer_Tick
ButtonTimer.Dispose()
'Enable Button
Button1.Enabled = True
End Sub
These are the important lines:
ButtonCountDown = 24
ButtonTimer.Interval = 1000 * 60 * 60 'Every 1 Hour
The above example will check the timer every hour and countdown from 24, thus 24 hours.
For testing purposes, change to minutes:
ButtonCountDown = 2
ButtonTimer.Interval = 1000 * 60 'Every 1 Minute
Now the button will disable for 2 minutes (timer checks every minute).
For testing purposes, change to seconds:
ButtonCountDown = 20
ButtonTimer.Interval = 1000 'Every 1 Second
Now the button will disable for 20 seconds (timer checks every second).

Detecting mouse moves and key strokes in vb.net

i want that when user is idle for some particular time and mouse doesnot moves on system than it starts counting time from then ownwards and when user moves mouse then time stops and i can save this time in a varianble
You can use the GetLastInputInfo API call.
The following code is mainly from here: http://pinvoke.net/default.aspx/user32/GetLastInputInfo.html
Imports System.Runtime.InteropServices
Public Class Form1
<StructLayout(LayoutKind.Sequential)> _
Structure LASTINPUTINFO
<MarshalAs(UnmanagedType.U4)> _
Public cbSize As Integer
<MarshalAs(UnmanagedType.U4)> _
Public dwTime As Integer
End Structure
<DllImport("user32.dll")> _
Shared Function GetLastInputInfo(ByRef plii As LASTINPUTINFO) As Boolean
End Function
Dim idletime As Integer
Dim lastInputInf As New LASTINPUTINFO()
Public Function GetLastInputTime() As Integer
idletime = 0
lastInputInf.cbSize = Marshal.SizeOf(lastInputInf)
lastInputInf.dwTime = 0
If GetLastInputInfo(lastInputInf) Then
idletime = Environment.TickCount - lastInputInf.dwTime
End If
If idletime > 0 Then
Return idletime / 1000
Else : Return 0
End If
End Function
Private sumofidletime As TimeSpan = New TimeSpan(0)
Private LastLastIdletime As Integer = 0
Private Sub Timer1_Tick(sender As Object, e As EventArgs) Handles Timer1.Tick
Dim it As Integer = GetLastInputTime()
If LastLastIdletime > it Then
Label1.Text = "IDLE STATE CHANGED!"
sumofidletime = sumofidletime.Add(TimeSpan.FromSeconds(LastLastIdletime))
Label2.Text = "Sum of idle time: " & sumofidletime.ToString
Else
Label1.Text = GetLastInputTime()
End If
LastLastIdletime = it
End Sub
End Class
This code displays the seconds the user has been idle since the last input action in the label on every timer tick. It also checks if the idle state has changed. So at this point you can react to it and save the LastLastIdletime as the amount of time in seconds that the user was inactive.
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

VB.net - Timer isn't updating

I'm trying to add an uptime counter so that from the moment my application launches it starts a timer that increments by the second until the application is closed or I stop it on purpose.
Currently the timer counts the first second and then stops. This might be me not understanding the tick function? I assume that the interval I set for the timer will refresh or loop the code within the tick sub? (Could me massively wrong).
I have timer1 and I've set it to "Enabled" and the interval to "1000" for one second.
In my Timer1_Tick Sub I have this:
Private Sub Timer1_Tick(sender As Object, e As EventArgs) Handles Timer1.Tick
Dim seconds, minutes, hours As Integer
If seconds = 60 Then
seconds = 0
minutes = minutes + 1
End If
If minutes = 60 Then
If seconds = 60 Then
seconds = 0
minutes = 0
hours = hours + 1
End If
End If
seconds = seconds + 1
Label44.Text = Format(hours, "00") & "." & Format(minutes, "00") & "." & Format(seconds, "00")
End Sub
In Form1_Load I have Timer1.Start()
Please can you tell me what I'm missing? Thanks.
For up time in my applications I just log the time and date it was started, then use a label to show difference in time since the time was logged. It's a lot simpler than running a time ticking all the time.
The approaches given are highly inaccurate because they assume that the tick event fires exactly at the specified interval, and that doesn't happen.
The tick event should be used only to update the label from a more precise time measurement. In the code below a stopwatch is used.
Dim appruntime As Stopwatch = Stopwatch.StartNew
Private Sub Timer1_Tick(sender As Object, e As EventArgs) Handles Timer1.Tick
Label1.Text = appruntime.Elapsed.ToString("d\ hh\:mm\:ss")
End Sub
You need to declare the variables within Form1.
Public Class Form1
Private seconds, minutes, hours As Integer
Private Sub Timer1_Tick(sender As System.Object, e As System.EventArgs) Handles Timer1.Tick
If seconds = 60 Then
seconds = 0
minutes = minutes + 1
End If
If minutes = 60 Then
If seconds = 60 Then
seconds = 0
minutes = 0
hours = hours + 1
End If
End If
seconds = seconds + 1
Label44.Text = Format(hours, "00") & "." & Format(minutes, "00") & "." & Format(seconds, "00")
End Sub
End Class