How to create Stopwatch in C#

Now we are going to learn about how to create a stop stopwatch in C#.
  • 8309

Introduction

Stopwatch is a very useful in our real life. It is used to count time elapsed. We use three buttons for stopwatch first "start"to start the stopwatch, Second "stop" and third button used for reset the stopwatch.

Example

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
namespace WindowsFormsApplication8
{
 public partial class Form1 :
Form
    {
      int ms, s, m, h;
        public Form1()
{
   InitializeComponent();
         ms = 0;
        }
        private void timer1_Tick(object sender, EventArgs e)
        {
            ms = ms + 1;
            if (ms == 9)
            {
                ms = 0;
                s = s + 1;
                lblsecond.Text = s.ToString();              
                if (s == 59)
                {
                    s = 0;
                    m = m + 1;
                    lblmin.Text = m.ToString();
                    if (m == 59)
                    {
                   m = 0;
                        h = h + 1;
                        lblhur.Text = h.ToString();
                        {
                            lblmsec.Text = ms.ToString();} } } }}                     
        private void button1_Click(object sender, EventArgs e)
        {
            timer1.Enabled = true;
        }
        private void button2_Click(object sender, EventArgs e)
       {            timer1.Enabled = false;
        }
        private void button3_Click(object sender, EventArgs e)
        {
            ms = 0;
            h = 0;
            s = 0;
            m = 0;
            timer1.Enabled = false;
            lblhur.Text = "00";
            lblmin.Text = "00";
            lblsecond.Text = "00";
            lblmsec.Text = "00";
        } } }

Output   

stopwatchstart.jpg

© 2013 dotNetheaven. All rights reserved.