C# 如何做30分钟倒计时

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/16620234/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-10 01:29:26  来源:igfitidea点击:

How to do a 30 minute count down timer

c#timer

提问by IceDawg

I want my textbox1.Textto countdown for 30 minutes. So far I have this:

我要textbox1.Text倒计时30分钟。到目前为止,我有这个:

public partial class Form1 : Form
{
    public Form1()
    {
        InitializeComponent();
    }

    private void button1_Click(object sender, EventArgs e)
    {
        Timer timeX = new Timer();
        timeX.Interval = 1800000;
        timeX.Tick += new EventHandler(timeX_Tick);
    }

    void timeX_Tick(object sender, EventArgs e)
    {
        // what do i put here?
    }
}

However I'm now stumped. I checked Google for answers but couldn't find one matching my question.

但是,我现在很难过。我在谷歌上搜索了答案,但找不到与我的问题相符的答案。

采纳答案by Nomad101

If all you want to do is set the value of your Texbox to count down from 30 Minutes. You will first need to change your timer interval to something smaller than 30Minutes. Something like timeX.Interval = 1000;which will fire every second. then set up your event like so:

如果您只想将 Texbox 的值设置为从 30 分钟开始倒计时。您首先需要将计时器间隔更改为小于 30 分钟。类似的东西timeX.Interval = 1000;每秒都会触发。然后像这样设置您的活动:

 int OrigTime = 1800;
 void timeX_Tick(object sender, EventArgs e)
 {
     OrigTime--;
     textBox1.Text = OrigTime/60 + ":" + ((OrigTime % 60) >= 10 ?  (OrigTime % 60).ToString() : "0" + OrigTime % 60);
 }

Also in your button click, you must add the following line: timeX.Enabled = true;In order to start the timer.

同样在您的按钮单击中,您必须添加以下行:timeX.Enabled = true;为了启动计时器。

回答by Sten Petrov

Your code will only get one event fired, once the 30 minutes has passed. In order to keep updating your UI continuously you'll have to make the events more frequent and add a condition inside the event handler to tell the count-down to stop once 30 minutes has passed.

一旦 30 分钟过去,您的代码只会触发一个事件。为了不断更新您的 UI,您必须使事件更频繁,并在事件处理程序中添加一个条件,告诉倒计时在 30 分钟过去后停止。

You can do the time calculations easily by using TimeSpan and DateTime.

您可以使用 TimeSpan 和 DateTime 轻松进行时间计算。

You'll also want to make sure your UI code runs on the UI thread, hence the Invoke.

您还需要确保您的 UI 代码在 UI 线程上运行,因此Invoke.

  timeX.Interval = 500;

...


  TimeSpan timeSpan = TimeSpan.FromMinutes(30);
  DataTime startedAt = DateTime.Now;
  void timeX_Tick(object sender, EventArgs e)
  { 
       if ((DateTime.Now - startedAt)<timeSpan){
          Invoke(()=>{
             TimeSpan remaining = timeSpan - (DateTime.Now - startedAt);
             textBox.Text = remaining.ToString(); 
          });
       } else
          timeX.Stop();
  }

回答by dharmatech

Here's a simple example similar to the code you posted:

这是一个类似于您发布的代码的简单示例:

using System;
using System.Windows.Forms;

namespace StackOverflowCountDown
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();

            textBox1.Text = TimeSpan.FromMinutes(30).ToString();
        }

        private void Form1_Load(object sender, EventArgs e) { }

        private void textBox1_TextChanged(object sender, EventArgs e) { }

        private void button1_Click(object sender, EventArgs e)
        {
            var startTime = DateTime.Now;

            var timer = new Timer() { Interval = 1000 };

            timer.Tick += (obj, args) =>    
                textBox1.Text =
                    (TimeSpan.FromMinutes(30) - (DateTime.Now - startTime))
                    .ToString("hh\:mm\:ss");

            timer.Enabled = true;
        }
    }
}

回答by eried

Easiest thing you can do, is use a 1 minute timer:

您可以做的最简单的事情是使用 1 分钟计时器:

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;

namespace countdowntimer
{
    public partial class Form1 : Form
    {
        private Timer timeX;
        private int minutesLeft;

        public Form1()
        {
            InitializeComponent();

            timeX = new Timer(){Interval = 60000};
            timeX.Tick += new EventHandler(timeX_Tick);
        }

        private void textBox1_TextChanged(object sender, EventArgs e)
        {



        }

        private void button1_Click(object sender, EventArgs e)
        {
            minutesLeft=30;
            timeX.Start();
        }

        void timeX_Tick(object sender, EventArgs e)
        {

            if(minutesLeft--<=0)
            {
              timeX.Stop();
              // Done!
            }
            else
            {
              // Not done yet...
            }
            textBox1.Text = minutesLeft + " mins remaining";
        }

    }
}

回答by Tanmay Nehete

try this hope this will work for u

试试这个希望这对你有用

set timer interval=1000

设置定时器间隔=1000

minremain=1800000; //Should be in milisecond
timerplurg.satrt();

 private void timerplurg_Tick(object sender, EventArgs e)
        {
       minremain = minremain - 1000;
        string Sec = string.Empty;
        string Min = string.Empty;
        if (minremain <= 0)
        {
            lblpurgingTimer.Text = "";
            timerplurg.Stop();
            return;
        }
        else
        {
            var timeSpan = TimeSpan.FromMilliseconds(Convert.ToDouble(minremain));

            var seconds = timeSpan.Seconds;
            var minutes = timeSpan.Minutes;
            if (seconds.ToString().Length.Equals(1))
            {
                Sec = "0" + seconds.ToString();
            }
            else
            {
                Sec = seconds.ToString();
            }
            if (minutes.ToString().Length.Equals(1))
            {
                Min = "0" + minutes.ToString();
            }
            else
            {
                Min = minutes.ToString();
            }
            string Totaltime = "Purge Remaing Time: " + Min + ":" + Sec;
            lblpurgingTimer.Text = Totaltime;
            }
         }