Introduction
The code for this Windows application is so compact, it is presented here inline. Belying its small size, however, the app actually solves a real-world problem, namely the need to measure events of a few minutes' duration to about a half-second granularity. How long does Photoshop take to launch? How long have I been on the phone? "I'll bring your stapler back in five minutes." Yeah, right. The Radio Shack Deluxe Sports Stopwatch (63-5017) costs $19.99.
Background
This is my entry in the imaginary "smallest useful app" contest--the entire app requires just 16 lines of user code. Thanks to .NET, the exe file is just 12.5k.
The Source Code
As they do in Microsoft Knowledgebase How-To articles, here are the step-by-step instructions:
- Start Microsoft Visual Studio .NET
- On the File menu, point to New, and then click Project
- Under Project Types, click Visual Basic Projects
- Under Templates, click Windows Application.
Form1
is created.
- Change
Form1
's Properties: .Text="Click to Start"
, .FormBorderStyle="FixedToolWindow"
, .Size="192,64"
- Place a new
Label
control anywhere on the form. Label1
is created.
- Change
Label1
's Properties: .Text="StopWatch"
, .Dock="Fill"
, .Font="Georgia, 24pt"
, .TextAlign="MiddleCenter"
. Select foreground and background colors to taste (the example is .BackColor=Hot Track
, .ForeColor=Menu
).
- Place a new
Timer
control on the form. Timer1
is created.
- Right-click Form1, and then click View Code
- Add the following code to the
Form1
class:
Dim startTime As DateTime
Private Sub Timer1_Tick(ByVal sender As System.Object, _
ByVal e As System.EventArgs) Handles Timer1.Tick
Dim span As TimeSpan = DateTime.Now.Subtract(startTime)
Label1.Text = span.Minutes.ToString & ":" & _
span.Seconds.ToString & "." & span.Milliseconds
End Sub
Private Sub Label1_Click(ByVal sender As System.Object, _
ByVal e As System.EventArgs) Handles Label1.Click
If (Timer1.Enabled) Then
Me.Text = "Click to Re-start"
Timer1.Stop()
Else
startTime = DateTime.Now()
Me.Text = "Click to Stop"
Timer1.Start()
End If
End Sub
To use the stopwatch, click inside its window. To stop it, click again. Clicking again will reset the stopwatch to 0:0.0 and start it counting again. For fancy effects like lap timing, just launch several copies of the StopWatch app at once.
Points of Interest
There is nothing very interesting here except how an app so simple and small can be surprisingly useful.
History
01/31/04 AD: Initial