Display time elapsed

后端 未结 3 579
谎友^
谎友^ 2021-01-24 13:30

I need to display the elapsed time dynamically. My code will pop up a message based on an interval value.

public void button1_Click(object sender, EventArgs e)
{         


        
相关标签:
3条回答
  • 2021-01-24 13:58

    I wouldn't muck about with timers. I'd use Microsoft's Reactive Framework for this. Just NuGet "Rx-Winforms" to get the bits. Then you can do this:

    Observable
        .Create<string>(o =>
        {
            var now = DateTimeOffset.Now;
            var end = now.AddMinutes(15.0);
            return
                Observable
                    .Interval(TimeSpan.FromSeconds(0.1))
                    .TakeUntil(end)
                    .Select(x => end.Subtract(DateTimeOffset.Now).ToString(@"mm\:ss"))
                    .DistinctUntilChanged()
                    .Subscribe(o);
        })
        .ObserveOn(this)
        .Subscribe(x => label1.Text = x);
    

    This will automatically create a countdown timer that will update the text in label1 with the following values:

    14:59 
    14:58 
    14:57 
    14:56 
    14:55 
    14:54 
    ...
    00:02
    00:01
    00:00
    

    If you want to stop this before the timer runs out the Subscribe method returns an IDisposable that you can just call .Dispose().

    0 讨论(0)
  • 2021-01-24 14:02

    You should store end-time in a filed at form level and then in Tick event handler of the timer check the difference between the end-time and now and update a label which you want to show count-down timer:

    private DateTime endTime;
    System.Windows.Forms.Timer timer = new System.Windows.Forms.Timer();
    private void button1_Click(object sender, EventArgs e)
    {
        var minutes = 0;
        if (int.TryParse(textBox1.Text, out minutes) && timer.Enabled == false)
        {
            endTime = DateTime.Now.AddMinutes(minutes);
            timer.Interval = 1000;
            timer.Tick -= new EventHandler(timer_Tick);
            timer.Tick += new EventHandler(timer_Tick);
            timer.Start();
            UpdateText();
        }
    }
    void timer_Tick(object sender, EventArgs e)
    {
        UpdateText();
    }
    void UpdateText()
    {
        var diff = endTime.Subtract(DateTime.Now);
        if (diff.TotalSeconds > 0)
            label1.Text = string.Format("{0:D2}:{1:D2}:{2:D2}",
                                       diff.Hours, diff.Minutes, diff.Seconds);
        else
        {
            this.Text = "00:00:00";
            timer.Enabled = false;
        }
    }
    
    0 讨论(0)
  • 2021-01-24 14:12

    You should try to count the 15 minutes. For example, if your using a Label (Label1) you should count it with a timer. Just use a timer and count every tick (1000 milliseconds) +1

    Timer1 has a +1 (declare a int as 0)
    If the label reaches the number of seconds or minutes
    (You can modify that with milliseconds), it stops the timer.
    
    0 讨论(0)
提交回复
热议问题