VB Code:
Public Class Stopwatch Private startTime As Date Private m_Elapsed As TimeSpan Private m_Running As Boolean ''' <summary> ''' The amount of time that has elapsed. ''' </summary> Public ReadOnly Property Elapsed() As TimeSpan Get Dim time As TimeSpan = Me.m_Elapsed If Me.m_Running Then time = time.Add(Date.Now.Subtract(Me.startTime)) End If Return time End Get End Property ''' <summary> ''' Indicates whether the stopwatch is currently timing or not. ''' </summary> Public ReadOnly Property Running() As Boolean Get Return Me.m_Running End Get End Property ''' <summary> ''' Creates a new Stopwatch object. ''' </summary> Public Sub New() ' Initialise with no time elapsed. Me.m_Elapsed = TimeSpan.Zero Me.m_Running = False End Sub ''' <summary> ''' Starts the stopwatch. ''' </summary> ''' <returns> ''' True if the stopwatch was started; False if the stopwatch was already running. ''' </returns> Public Function Start() As Boolean Dim result As Boolean = Not Me.m_Running If result Then Me.startTime = Date.Now Me.m_Running = True End If Return result End Function ''' <summary> ''' Stops the stopwatch. ''' </summary> ''' <returns> ''' True if the stopwatch was stopped; False if the stopwatch was not running. ''' </returns> Public Function [Stop]() As Boolean Dim result As Boolean = Me.m_Running If result Then Me.m_Elapsed = Me.m_Elapsed.Add(Date.Now.Subtract(Me.startTime)) Me.m_Running = False End If Return result End Function ''' <summary> ''' Resets the elapsed time to zero. ''' </summary> Public Sub Reset() ' Set the start time in case the stopwatch is running. Me.startTime = Date.Now Me.m_Elapsed = TimeSpan.Zero End Sub End Class


Reply With Quote