Display time elapsed

后端 未结 3 584
谎友^
谎友^ 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 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;
        }
    }
    

提交回复
热议问题