Hack Forums
[.NET] How to create a Simple StopWatch - Printable Version

+- Hack Forums (https://hackforums.net)
+-- Forum: Tech (https://hackforums.net/forumdisplay.php?fid=444)
+--- Forum: Coding (https://hackforums.net/forumdisplay.php?fid=151)
+---- Forum: Software Development (https://hackforums.net/forumdisplay.php?fid=118)
+---- Thread: [.NET] How to create a Simple StopWatch (/showthread.php?tid=4978598)



How to create a Simple StopWatch - VmX5 - Sep 6, 2015

Okay so Never posted in a while and this seems to difficult to many beginners so decided to do a tutorial on a Simple Stop watch! So Lets get started!

This StopWatch consists of

1 Label - Named "Time" - Format : HOURS:MIN:SEC:MILSEC
4 Buttons - Start, Stop, Lap, Reset
1 Timer - Interval = 1, Enabled = False
1 Listbox

I made mine look like this :

[Image: 93c36e1615bbaadef688ee8a81e329e7.png]


Okay So lets see the code!

Before we get started we need to declare 2 variables below the Public Class Form1 line

Code
Dim sWatch As New Diagnostics.Stopwatch
    Dim Lap As Integer

Now we have declared our Variables for a stopwatch and Lap Count we can start with out buttons

Start Button :
Code
Timer1.Start() 'Its as simple as that because the Main code will be within the timer.

Stop Button :
Code
Timer1.Stop()

This will be the code for our Lap Button
Code
Lap = Lap + 1
        ListBox1.Items.Add("Lap " & Lap.ToString & " - " & Time.Text)
        'Will add a item to the listbox with the lap count and current time example (Lap 1 - 00:01:52:235 )

Reset Button :
Code
sWatch.Stop()
        sWatch.Reset()
        Lap = 0
        Timer1.Stop()
        ListBox1.Items.Clear()
        Time.Text = "00:00:00:000"
       'All This does is reset all the variables, the label, and the listbox to its default state.

And Finally this is the CORE of the program, The Timer!
Code
Dim tSpan As TimeSpan = sWatch.Elapsed
        Time.Text = String.Format("{0:00}:{1:00}:{2:00}:{3:00}", Math.Floor(tSpan.TotalHours), tSpan.Minutes, tSpan.Seconds, tSpan.Milliseconds)


If enough people want then I'll make a tutorial on a Alarm!


* - asdfghjklwertyuio345678 - Sep 7, 2015

This is good to use on timers when auto refreshing web pages etc. Good share man.


* - BahNahNah - Sep 7, 2015

(Sep 7, 2015 12:22 AM)Ja-ke Wrote:  This is good to use on timers when auto refreshing web pages etc. Good share man.

Or just use a timer? 🤮


* - nathan72389 - Sep 7, 2015

Or you know you could of just used the stopwatch class.


* - LordCoder - Sep 7, 2015

Timer and Stopwatch? lol.


* - asdfghjklwertyuio345678 - Sep 9, 2015

(Sep 7, 2015 03:43 AM)BahNahNah Wrote:  Or just use a timer? 🤮

You could use both. Have the stopwatch counting inside the timer. 🙂

Code
using System.Diagnostics;

Stopwatch Stopwatch = new Stopwatch();

// add to button1 click
Stopwatch.Reset();
Stopwatch.Start();
timer1.Start();

// add to timer1 tick
if(Stopwatch.Elapsed.Seconds == 10)
{
    // Do something after 10 second mark is reached
}