Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Set start time for Stopwatch program in C#

Tags:

c#

stopwatch

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.

like image 349
Kyle Dam Avatar asked Nov 27 '22 21:11

Kyle Dam


1 Answers

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;
            }
        }
    }
like image 140
Eric J. Avatar answered Dec 08 '22 11:12

Eric J.