Set start time for Stopwatch program in C#

Kyle Dam picture Kyle Dam · Jul 27, 2012 · Viewed 19.3k times · Source

I want to write a simple stopwatch program, I can make it work with the following code

    public Form1()
    {
        InitializeComponent();
    }
    System.Diagnostics.Stopwatch ss = new System.Diagnostics.Stopwatch { };
    private void button1_Click(object sender, EventArgs e)
    {
        if (button1.Text == "Start")
        {
            button1.Text = "Stop";

            ss.Start();
            timer1.Enabled = true;

        }
        else
        {
            button1.Text = "Start";

            ss.Stop();
            timer1.Enabled = false;

        }
    }

    private void timer1_Tick(object sender, EventArgs e)
    {


            int hrs = ss.Elapsed.Hours, mins = ss.Elapsed.Minutes, secs = ss.Elapsed.Seconds;
            label1.Text = hrs + ":";
            if (mins < 10)
                label1.Text += "0" + mins + ":";
            else
                label1.Text += mins + ":";
            if (secs < 10)
                label1.Text += "0" + secs;
            else
                label1.Text += secs;


    }

    private void button2_Click(object sender, EventArgs e)
    {
        ss.Reset();
       button1.Text= "Start";
       timer1.Enabled = true;

    }

Now I want to set a custom start time for this stopwatch, for example I want it not to begin count up from 0:00:00 but to start with 0:45:00 How can I do it, thank you.

Answer

Eric J. picture Eric J. · Jul 27, 2012

Stopwatch does not have any methods or properties that would allow you to set a custom start time.

You can subclass Stopwatch and override ElapsedMilliseconds and ElapsedTicks to adjust for your start time offset.

    public class MyStopwatch : Stopwatch
    {
        public TimeSpan StartOffset { get; private set; }

        public MyStopwatch(TimeSpan startOffset)
        {
            StartOffset = startOffset;
        }

        public new long ElapsedMilliseconds
        {
            get
            {
                return base.ElapsedMilliseconds + (long)StartOffset.TotalMilliseconds;
            }
        }

        public new long ElapsedTicks
        {
            get
            {
                return base.ElapsedTicks + StartOffset.Ticks;
            }
        }
    }