-
March 18th, 2011, 11:35 PM
#1
[RESOLVED] Simple Stopwatch Application
Ok, so i'm trying to get back into the swing of C# and it's slowly coming back to me but I have a slight problem. I'm making a simple stop watch program that is supposed to print the time as it ticks in a windows form app. It's as simple as:
Code:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Diagnostics;
using System.Threading;
namespace WindowsFormsApplication1
{
public partial class Form1 : Form
{
Stopwatch stopWatch = new Stopwatch();
public Form1()
{
InitializeComponent();
}
private void start_Click(object sender, EventArgs e)
{
stopWatch.Start();
}
private void stop_Click(object sender, EventArgs e)
{
stopWatch.Stop();
timePrint();
}
private void reset_Click(object sender, EventArgs e)
{
stopWatch = Stopwatch.StartNew();
}
private void timePrint()
{
label1.Text = stopWatch.ElapsedTicks.ToString();
hours.Text = "Time elapsed: " + stopWatch.Elapsed;
}
}
}
It doesn't quite update the label as the stopwatch counts though. I can do it in as a CMD line app but I didn't want to do the application in cmd line form. Any suggestions?
-
March 18th, 2011, 11:46 PM
#2
Re: Simple Stopwatch Application
You need to create a timer for the app and handle the timer event.
Set the timer resolution to something somewhat fast and in the handler read the stopwatch value and update the text box.
Use the form designer to drag a timer object onto your form. Then click the little lightning bolt in the properties window to add the Tick event handler.
-
March 18th, 2011, 11:51 PM
#3
Re: Simple Stopwatch Application
If I use the timer object will I still need the Stowatch() class?
-
March 19th, 2011, 11:38 AM
#4
Re: Simple Stopwatch Application
Originally Posted by Howdy_McGee
If I use the timer object will I still need the Stowatch() class?
Probably yes because it serves a different responsibility. The stopwatch class would contain the current timing and allow you to format the display as you which. The timer exists solely to update the display.
If you only used the timer, then the accuracy may suffer. This is because user interaction (such as moving the mouse) could interfere with the timer click. If you use the stopwatch the elapsed time will be correct even though the display update may not happen on precisely every interval (i.e for a 100ms resolution, the actual timer click may be at 101ms or 104ms, etc).
Posting Permissions
- You may not post new threads
- You may not post replies
- You may not post attachments
- You may not edit your posts
-
Forum Rules
|
Click Here to Expand Forum to Full Width
|