Set start time for Stopwatch program in C#

后端 未结 5 2274
粉色の甜心
粉色の甜心 2021-01-06 09:29

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

    public Form1()
    {
        InitializeComponent();
    }
    Syst         


        
5条回答
  •  忘掉有多难
    2021-01-06 09:55

    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;
                }
            }
        }
    

提交回复
热议问题