VB Code:
  1. Public Class Stopwatch
  2.  
  3.     Private startTime As Date
  4.     Private m_Elapsed As TimeSpan
  5.     Private m_Running As Boolean
  6.  
  7.     ''' <summary>
  8.     ''' The amount of time that has elapsed.
  9.     ''' </summary>
  10.     Public ReadOnly Property Elapsed() As TimeSpan
  11.         Get
  12.             Dim time As TimeSpan = Me.m_Elapsed
  13.  
  14.             If Me.m_Running Then
  15.                 time = time.Add(Date.Now.Subtract(Me.startTime))
  16.             End If
  17.  
  18.             Return time
  19.         End Get
  20.     End Property
  21.  
  22.     ''' <summary>
  23.     ''' Indicates whether the stopwatch is currently timing or not.
  24.     ''' </summary>
  25.     Public ReadOnly Property Running() As Boolean
  26.         Get
  27.             Return Me.m_Running
  28.         End Get
  29.     End Property
  30.  
  31.     ''' <summary>
  32.     ''' Creates a new Stopwatch object.
  33.     ''' </summary>
  34.     Public Sub New()
  35.         ' Initialise with no time elapsed.
  36.         Me.m_Elapsed = TimeSpan.Zero
  37.         Me.m_Running = False
  38.     End Sub
  39.  
  40.     ''' <summary>
  41.     ''' Starts the stopwatch.
  42.     ''' </summary>
  43.     ''' <returns>
  44.     ''' True if the stopwatch was started; False if the stopwatch was already running.
  45.     ''' </returns>
  46.     Public Function Start() As Boolean
  47.         Dim result As Boolean = Not Me.m_Running
  48.  
  49.         If result Then
  50.             Me.startTime = Date.Now
  51.             Me.m_Running = True
  52.         End If
  53.  
  54.         Return result
  55.     End Function
  56.  
  57.     ''' <summary>
  58.     ''' Stops the stopwatch.
  59.     ''' </summary>
  60.     ''' <returns>
  61.     ''' True if the stopwatch was stopped; False if the stopwatch was not running.
  62.     ''' </returns>
  63.     Public Function [Stop]() As Boolean
  64.         Dim result As Boolean = Me.m_Running
  65.  
  66.         If result Then
  67.             Me.m_Elapsed = Me.m_Elapsed.Add(Date.Now.Subtract(Me.startTime))
  68.             Me.m_Running = False
  69.         End If
  70.  
  71.         Return result
  72.     End Function
  73.  
  74.     ''' <summary>
  75.     ''' Resets the elapsed time to zero.
  76.     ''' </summary>
  77.     Public Sub Reset()
  78.         ' Set the start time in case the stopwatch is running.
  79.         Me.startTime = Date.Now
  80.         Me.m_Elapsed = TimeSpan.Zero
  81.     End Sub
  82.  
  83. End Class