Results 1 to 17 of 17

Thread: [RESOLVED] I Need a Stopwatch

  1. #1

    Thread Starter
    Lively Member cevem's Avatar
    Join Date
    Feb 2010
    Location
    Mars
    Posts
    78

    Resolved [RESOLVED] I Need a Stopwatch

    Hi.

    I'm searching a stopwatch like: HH:MM:SS. I need start and pause buttons. How i do this? Thanks.

  2. #2
    VB Addict Pradeep1210's Avatar
    Join Date
    Apr 2004
    Location
    Inside the CPU...
    Posts
    6,614

    Re: I Need a Stopwatch

    Put a Label and Timer on a form and the following code:
    vb.net Code:
    1. Private Sub Form2_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
    2.     Timer1.Interval = 500
    3.     Timer1.Start()
    4. End Sub
    5.  
    6. Private Sub Timer1_Tick(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Timer1.Tick
    7.     Label1.Text = Now.ToString("hh:mm:ss")
    8. End Sub
    Pradeep, Microsoft MVP (Visual Basic)
    Please appreciate posts that have helped you by clicking icon on the left of the post.
    "A problem well stated is a problem half solved." — Charles F. Kettering

    Read articles on My Blog101 LINQ SamplesJSON ValidatorXML Schema Validator"How Do I" videos on MSDNVB.NET and C# ComparisonGood Coding PracticesVBForums Reputation SaverString EnumSuper Simple Tetris Game


    (2010-2013)
    NB: I do not answer coding questions via PM. If you want my help, then make a post and PM me it's link. If I can help, trust me I will...

  3. #3
    Super Moderator Shaggy Hiker's Avatar
    Join Date
    Aug 2002
    Location
    Idaho
    Posts
    40,106

    Re: I Need a Stopwatch

    You might also want to look at the Stopwatch object. That has Stop, Start, and Reset methods built in, but it is mostly used for precision timing, so you might have to do some formatting on the output.
    My usual boring signature: Nothing

  4. #4
    Powered By Medtronic dbasnett's Avatar
    Join Date
    Dec 2007
    Location
    Jefferson City, MO
    Posts
    9,897

    Re: I Need a Stopwatch

    Use both ideas. The StopWatch object to keep track of the time, and the Timer to update the display. Your buttons would manipulate them as needed.
    My First Computer -- Documentation Link (RT?M) -- Using the Debugger -- Prime Number Sieve
    Counting Bits -- Subnet Calculator -- UI Guidelines -- >> SerialPort Answer <<

    "Those who use Application.DoEvents have no idea what it does and those who know what it does never use it." John Wein

  5. #5
    PowerPoster make me rain's Avatar
    Join Date
    Sep 2008
    Location
    india/Hubli
    Posts
    2,208

    Re: I Need a Stopwatch

    place a label control + timer control
    set timer control interval to 1

    declare variables at the top of your form so that the variables must be visible
    to all the sub procedures

    vb.net Code:
    1. Dim MiliSecond As Integer
    2.     Dim OneSecondEquals As Int16
    3.     Dim OneMinuteEquals As Int16
    4.     Dim OneHourEquals As Int16
    5.     Dim OutPutTest As String

    timer controls tick event use the code
    vb.net Code:
    1. If MiliSecond = 60 Then
    2.             OneSecondEquals = OneSecondEquals + 1
    3.             MiliSecond = 0
    4.         End If
    5.  
    6.         If OneSecondEquals = 60 Then
    7.             OneMinuteEquals = OneMinuteEquals + 1
    8.             OneSecondEquals = 0
    9.         End If
    10.  
    11.         If OneMinuteEquals = 60 Then
    12.             OneHourEquals = OneHourEquals + 1
    13.             OneMinuteEquals = 0
    14.         End If
    15.         MiliSecond = MiliSecond + 1
    16.         OutPutTest = OneHourEquals & ":" & OneMinuteEquals & ":" & OneSecondEquals & ":" & MiliSecond
    17.  
    18.         Me.lbl_StopWatch.Text = OutPutTest

    to pause the timer use
    vb.net Code:
    1. Me.TiMeR_runStopWatch.Stop()
    to reset the timer u need to clear the variables declared
    vb.net Code:
    1. MiliSecond = 0
    2.      OneSecondEquals  = 0
    3.     OneMinuteEquals = 0
    4.     OneHourEquals = 0
    5.    OutPutTest= "00:00:00:00"
    The averted nuclear war
    My notes:

    PrOtect your PC. MSDN Functions .OOP LINUX forum
    .LINQ LINQ videous
    If some one helps you please rate them with out fail , forum doesn't expects any thing other than this

  6. #6
    Powered By Medtronic dbasnett's Avatar
    Join Date
    Dec 2007
    Location
    Jefferson City, MO
    Posts
    9,897

    Re: I Need a Stopwatch

    @make_me - never use the Timer to accumulate time. That method assumes that the timer fires exactly on the interval specified, which is an incorrect assumption.

    Here is some code that illustrates the point:

    Code:
    Public Class Form1
        'a project with a Timer, Button, and 2 Labels
        Private Sub Form1_Shown(ByVal sender As Object, _
                                ByVal e As System.EventArgs) Handles Me.Shown
            Timer1.Interval = 1000 'one second
        End Sub
    
        Dim start As DateTime
        Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
            'click and watch the display for a couple of Minutes
            Timer1.Start()
            start = DateTime.Now
            Button1.Enabled = False
        End Sub
    
        Private Sub Timer1_Tick(ByVal sender As System.Object, _
                                ByVal e As System.EventArgs) Handles Timer1.Tick
            Static mySecs As Integer = 0
            mySecs += 1
            Dim et As TimeSpan = DateTime.Now - start
            'Surprised by what you see in the labels?
            Label1.Text = mySecs.ToString("n0")
            Label2.Text = et.TotalSeconds.ToString("n0")
        End Sub
    End Class
    On my PC the error 1 second per minute roughly.
    Last edited by dbasnett; Jun 28th, 2011 at 09:26 AM.
    My First Computer -- Documentation Link (RT?M) -- Using the Debugger -- Prime Number Sieve
    Counting Bits -- Subnet Calculator -- UI Guidelines -- >> SerialPort Answer <<

    "Those who use Application.DoEvents have no idea what it does and those who know what it does never use it." John Wein

  7. #7
    PowerPoster make me rain's Avatar
    Join Date
    Sep 2008
    Location
    india/Hubli
    Posts
    2,208

    Re: I Need a Stopwatch

    Dbas thanks for the alert
    but i have checked up to 1000 sec but didn't found any difference

    i would like to request pradeep & shaggy for the check please
    The averted nuclear war
    My notes:

    PrOtect your PC. MSDN Functions .OOP LINUX forum
    .LINQ LINQ videous
    If some one helps you please rate them with out fail , forum doesn't expects any thing other than this

  8. #8
    Master Of Orion ForumAccount's Avatar
    Join Date
    Jan 2009
    Location
    Canada
    Posts
    2,802

    Re: I Need a Stopwatch

    On my PC the error 1 second per minute roughly.
    I can confirm about the same error rate.

  9. #9
    Super Moderator Shaggy Hiker's Avatar
    Join Date
    Aug 2002
    Location
    Idaho
    Posts
    40,106

    Re: I Need a Stopwatch

    I'm not going to check, I know it's true, but it won't be true on every computer, or for every time you run it. Consider it this way:

    The timer raises Tick events whenever the elapsed time is greater than the interval of the timer. That has at least two different places that it can fail. The first place is that the timer may not get to check the elapsed time as often as you would like. If the interval is 400, and the timer checks the elapsed time at 398, it will find that the interval has not been exceeded, but perhaps it doesn't get to check again until 405, in which case it will raise the event, but will be late in doing so. The second issue is that just raising the event is meaningless if the program is running so many things that the event doesn't get handled in a timely fashion. A variation on these issues is that if the computer is running so many things that the thread that has the timer doesn't get a serviced frequently, then the check of the elapsed time may be delayed, or the event may be delayed, or both.

    Either way, the timer is not always going to be reliable.
    My usual boring signature: Nothing

  10. #10
    VB For Fun Edgemeal's Avatar
    Join Date
    Sep 2006
    Location
    WindowFromPoint
    Posts
    4,255

    Re: I Need a Stopwatch

    Quote Originally Posted by dbasnett View Post
    Use both ideas. The StopWatch object to keep track of the time, and the Timer to update the display. Your buttons would manipulate them as needed.
    Since were on the subject, Why is milliseconds returned as 3 digits and not two digits? (see Function FormatSW).


    Code:
    Public Class Form1
       
        Dim sw As New Stopwatch
    
        ' // Return stopwatch elapsed time as "hh:mm:ss:ms" //
        Private Function FormatSW(ByVal sw As Stopwatch) As String
            With sw.Elapsed
                Return .Hours.ToString("00") _
                & ":" & .Minutes.ToString("00") _
                & ":" & .Seconds.ToString("00") _
                & "." & .Milliseconds.ToString("00") '< ms is shown as 3 digits, Why not 2 digits?
            End With
        End Function
    
        ' // Form Load - Setup //
        Private Sub Form1_Load(sender As System.Object, e As System.EventArgs) Handles MyBase.Load
            TmrDisplay.Stop() ' display timer off
            TmrDisplay.Interval = 200 ' display timer speed 
            LblElapsed.Text = "00:00:00:00" ' label default
            ' disable pause/stop buttons
            BtnPause.Enabled = False
            BtnStop.Enabled = False
        End Sub
    
        ' // start/restart button //
        Private Sub BtnStart_Click(sender As System.Object, e As System.EventArgs) Handles BtnStart.Click
            ' stop display timer
            TmrDisplay.Stop()
            'reset pause button color
            BtnPause.BackColor = SystemColors.Control
            ' enable pause/stop buttons
            BtnPause.Enabled = True
            BtnStop.Enabled = True
            ' reset stopwatch
            sw.Restart()
            ' reset label
            LblElapsed.Text = "00:00:00:00"
            ' start display timer
            TmrDisplay.Start()
        End Sub
    
        ' // stop button // 
        Private Sub BtnStop_Click(sender As System.Object, e As System.EventArgs) Handles BtnStop.Click
            ' stop stopwatch, timer
            sw.Stop()
            TmrDisplay.Stop()
            'reset pause button color
            BtnPause.BackColor = SystemColors.Control
            ' disable pause/stop buttons
            BtnPause.Enabled = False
            BtnStop.Enabled = False
        End Sub
    
        ' // pause button //
        Private Sub BtnPause_Click(sender As System.Object, e As System.EventArgs) Handles BtnPause.Click
            'toggle display timer
            TmrDisplay.Enabled = Not TmrDisplay.Enabled
    
            If TmrDisplay.Enabled = False Then
                ' pause stopwatch
                sw.Stop()
                ' set pause button to red
                BtnPause.BackColor = Color.Red
            Else
                ' resume stopwatch
                sw.Start()
                ' upate label with elapsed time
                LblElapsed.Text = FormatSW(sw)
                'reset pause button color
                BtnPause.BackColor = SystemColors.Control
            End If
        End Sub
    
        ' // Timer - display //
        Private Sub TmrDisplay_Tick(sender As System.Object, e As System.EventArgs) Handles TmrDisplay.Tick
            LblElapsed.Text = FormatSW(sw) ' upate label with elapsed sw time
        End Sub
    
    End Class

  11. #11
    Master Of Orion ForumAccount's Avatar
    Join Date
    Jan 2009
    Location
    Canada
    Posts
    2,802

    Re: I Need a Stopwatch

    There are 1000 milliseconds for each second 000-999. This is why it's 3 digits.

  12. #12
    VB For Fun Edgemeal's Avatar
    Join Date
    Sep 2006
    Location
    WindowFromPoint
    Posts
    4,255

    Re: I Need a Stopwatch

    Quote Originally Posted by ForumAccount View Post
    There are 1000 milliseconds for each second 000-999. This is why it's 3 digits.
    ya, For some reason I was expecting .ToString("00") to round off milliseconds to just two digits .

  13. #13
    VB Addict Pradeep1210's Avatar
    Join Date
    Apr 2004
    Location
    Inside the CPU...
    Posts
    6,614

    Re: I Need a Stopwatch

    Quote Originally Posted by Shaggy Hiker View Post
    I'm not going to check, I know it's true, ...
    same with me...
    What's the point in wasting time in something that is already known, tested and documented.
    Pradeep, Microsoft MVP (Visual Basic)
    Please appreciate posts that have helped you by clicking icon on the left of the post.
    "A problem well stated is a problem half solved." — Charles F. Kettering

    Read articles on My Blog101 LINQ SamplesJSON ValidatorXML Schema Validator"How Do I" videos on MSDNVB.NET and C# ComparisonGood Coding PracticesVBForums Reputation SaverString EnumSuper Simple Tetris Game


    (2010-2013)
    NB: I do not answer coding questions via PM. If you want my help, then make a post and PM me it's link. If I can help, trust me I will...

  14. #14
    Powered By Medtronic dbasnett's Avatar
    Join Date
    Dec 2007
    Location
    Jefferson City, MO
    Posts
    9,897

    Re: I Need a Stopwatch

    Quote Originally Posted by make me rain View Post
    Dbas thanks for the alert
    but i have checked up to 1000 sec but didn't found any difference

    i would like to request pradeep & shaggy for the check please
    You ran the code I posted and there was no difference? Though the sample is small everyone that has tried it, until now, has reported a variance. Odd.

    In .Net 4.0 you can specify format string for TimeSpans (the Elapsed part of the stopwatch).

    Code:
        Dim stpw As New Stopwatch
    
            Dim s As String = stpw.Elapsed.ToString("hh\:mm\:ss\.fff")
    My First Computer -- Documentation Link (RT?M) -- Using the Debugger -- Prime Number Sieve
    Counting Bits -- Subnet Calculator -- UI Guidelines -- >> SerialPort Answer <<

    "Those who use Application.DoEvents have no idea what it does and those who know what it does never use it." John Wein

  15. #15
    Powered By Medtronic dbasnett's Avatar
    Join Date
    Dec 2007
    Location
    Jefferson City, MO
    Posts
    9,897

    Re: I Need a Stopwatch

    Quote Originally Posted by Pradeep1210 View Post
    same with me...
    What's the point in wasting time in something that is already known, tested and documented.
    Yet it seems that several times a month someone tries to use the timer to track the time.
    My First Computer -- Documentation Link (RT?M) -- Using the Debugger -- Prime Number Sieve
    Counting Bits -- Subnet Calculator -- UI Guidelines -- >> SerialPort Answer <<

    "Those who use Application.DoEvents have no idea what it does and those who know what it does never use it." John Wein

  16. #16

    Thread Starter
    Lively Member cevem's Avatar
    Join Date
    Feb 2010
    Location
    Mars
    Posts
    78

    Re: I Need a Stopwatch

    Quote Originally Posted by Edgemeal View Post
    Since were on the subject, Why is milliseconds returned as 3 digits and not two digits? (see Function FormatSW).


    Code:
    Public Class Form1
       
        Dim sw As New Stopwatch
    
        ' // Return stopwatch elapsed time as "hh:mm:ss:ms" //
        Private Function FormatSW(ByVal sw As Stopwatch) As String
            With sw.Elapsed
                Return .Hours.ToString("00") _
                & ":" & .Minutes.ToString("00") _
                & ":" & .Seconds.ToString("00") _
                & "." & .Milliseconds.ToString("00") '< ms is shown as 3 digits, Why not 2 digits?
            End With
        End Function
    
        ' // Form Load - Setup //
        Private Sub Form1_Load(sender As System.Object, e As System.EventArgs) Handles MyBase.Load
            TmrDisplay.Stop() ' display timer off
            TmrDisplay.Interval = 200 ' display timer speed 
            LblElapsed.Text = "00:00:00:00" ' label default
            ' disable pause/stop buttons
            BtnPause.Enabled = False
            BtnStop.Enabled = False
        End Sub
    
        ' // start/restart button //
        Private Sub BtnStart_Click(sender As System.Object, e As System.EventArgs) Handles BtnStart.Click
            ' stop display timer
            TmrDisplay.Stop()
            'reset pause button color
            BtnPause.BackColor = SystemColors.Control
            ' enable pause/stop buttons
            BtnPause.Enabled = True
            BtnStop.Enabled = True
            ' reset stopwatch
            sw.Restart()
            ' reset label
            LblElapsed.Text = "00:00:00:00"
            ' start display timer
            TmrDisplay.Start()
        End Sub
    
        ' // stop button // 
        Private Sub BtnStop_Click(sender As System.Object, e As System.EventArgs) Handles BtnStop.Click
            ' stop stopwatch, timer
            sw.Stop()
            TmrDisplay.Stop()
            'reset pause button color
            BtnPause.BackColor = SystemColors.Control
            ' disable pause/stop buttons
            BtnPause.Enabled = False
            BtnStop.Enabled = False
        End Sub
    
        ' // pause button //
        Private Sub BtnPause_Click(sender As System.Object, e As System.EventArgs) Handles BtnPause.Click
            'toggle display timer
            TmrDisplay.Enabled = Not TmrDisplay.Enabled
    
            If TmrDisplay.Enabled = False Then
                ' pause stopwatch
                sw.Stop()
                ' set pause button to red
                BtnPause.BackColor = Color.Red
            Else
                ' resume stopwatch
                sw.Start()
                ' upate label with elapsed time
                LblElapsed.Text = FormatSW(sw)
                'reset pause button color
                BtnPause.BackColor = SystemColors.Control
            End If
        End Sub
    
        ' // Timer - display //
        Private Sub TmrDisplay_Tick(sender As System.Object, e As System.EventArgs) Handles TmrDisplay.Tick
            LblElapsed.Text = FormatSW(sw) ' upate label with elapsed sw time
        End Sub
    
    End Class
    Thank you so much you and other guys. Code it's works.

  17. #17
    Powered By Medtronic dbasnett's Avatar
    Join Date
    Dec 2007
    Location
    Jefferson City, MO
    Posts
    9,897

    Re: [RESOLVED] I Need a Stopwatch

    Basically the same as edge's but with lap time

    Code:
    Public Class Form1
    
        'Button1 - Start
        'Button2 - Stop
        'Button3 - Pause
        'Button4 - Lap
        'Label1 - TOD
        'Label2 - Stopwatch elapsed time
        'Label3 - Last lap
    
        Dim stpw As New Stopwatch
        Dim WithEvents theTimer As New System.Windows.Forms.Timer
    
        Private Sub Button1_Click(sender As System.Object, _
                                  e As System.EventArgs) Handles Button1.Click
            ' Start
            Button1.Enabled = False 'only one start
            lastElap = New TimeSpan(0) 'reset lap time to zero
            stpw.Restart() 'stop, reset, start'start the clock, set the buttons
            Button2.Enabled = True
            Button3.Enabled = True
            Button4.Enabled = True
        End Sub
    
        Private Sub Button2_Click(sender As System.Object, _
                                  e As System.EventArgs) Handles Button2.Click
            ' Stop
            stpw.Stop() 'stop the clock, set buttons
            Button1.Enabled = True
            Button2.Enabled = False
            Button3.Enabled = False
            Button4.Enabled = False
            Button3.Text = "Pause" 'Set Button Text
        End Sub
    
        Private Sub Button3_Click(sender As System.Object, _
                                  e As System.EventArgs) Handles Button3.Click
            ' Pause
            If stpw.IsRunning Then 'stop if running
                stpw.Stop()
                Button3.Text = "Resume"
            Else 'else start
                stpw.Start()
                Button3.Text = "Pause"
            End If
        End Sub
    
        Dim lastElap As TimeSpan
        Private Sub Button4_Click(sender As System.Object, _
                                  e As System.EventArgs) Handles Button4.Click
            ' Lap
            Dim foo As TimeSpan = stpw.Elapsed 'get the current elapsed
            lastElap = foo - lastElap 'subtract previous elapsed
            Label3.Text = lastElap.ToString("hh\:mm\:ss\.fff") 'show the lap time hh:mm:ss.fff
            lastElap = foo 'store current elapsed
        End Sub
    
        Private Sub theTimer_Tick(sender As Object, _
                                  e As System.EventArgs) Handles theTimer.Tick
            'show the date and time
            Label1.Text = DateTime.Now.ToString("d-MMM-yyyy  HH:mm:ss.ff") 'show the current date time
            Label2.Text = stpw.Elapsed.ToString("hh\:mm\:ss\.fff") 'show the elapsed time hh:mm:ss.fff
        End Sub
    
        Private Sub Form1_Shown(sender As Object, _
                                e As System.EventArgs) Handles Me.Shown
            theTimer.Interval = 10 'the interval
            theTimer.Start() 'start the timer
            Button2.PerformClick() 'press stop
        End Sub
    End Class
    My First Computer -- Documentation Link (RT?M) -- Using the Debugger -- Prime Number Sieve
    Counting Bits -- Subnet Calculator -- UI Guidelines -- >> SerialPort Answer <<

    "Those who use Application.DoEvents have no idea what it does and those who know what it does never use it." John Wein

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  



Click Here to Expand Forum to Full Width