Таймер обратного отсчета секунд - PullRequest
11 голосов
/ 31 мая 2011

У меня есть lblCountdown со значением int 60. Я хочу, чтобы значение int lblCountDown уменьшалось с секундами, пока оно не достигло 0.

Это то, что у меня пока есть:

   private int counter = 60;
    private void button1_Click(object sender, EventArgs e)
    {
        int counter = 60;
        timer1 = new Timer();
        timer1.Tick += new EventHandler(timer1_Tick);
        timer1.Interval = 1000; // 1 second
        timer1.Start();
        label1.Text = counter.ToString();
    }

    private void timer1_Tick(object sender, EventArgs e)
    {
        counter--;
        if (counter == 0)

            timer1.Stop();
            label1.Text = counter.ToString();

    }

Ответы [ 6 ]

17 голосов
/ 31 мая 2011

Используйте таймер для этого

   private System.Windows.Forms.Timer timer1; 
   private int counter = 60;
   private void btnStart_Click_1(object sender, EventArgs e)
   {
        timer1 = new System.Windows.Forms.Timer();
        timer1.Tick += new EventHandler(timer1_Tick);
        timer1.Interval = 1000; // 1 second
        timer1.Start();
        lblCountDown.Text = counter.ToString();
    }

    private void timer1_Tick(object sender, EventArgs e)
    {
        counter--;
        if (counter == 0)
            timer1.Stop();
        lblCountDown.Text = counter.ToString();
    }
3 голосов
/ 02 июня 2015
int segundo = 0;
DateTime dt = new DateTime();

private void timer1_Tick(object sender, EventArgs e){
    segundo++;
    label1.Text = dt.AddSeconds(segundo).ToString("HH:mm:ss");
}
1 голос
/ 10 января 2019

enter image description here .

Использование:

CountDownTimer timer = new CountDownTimer();


//set to 30 mins
timer.SetTime(30,0);     

timer.Start();

//update label text
timer.TimeChanged += () => Label1.Text = timer.TimeLeftMsStr; 

// show messageBox on timer = 00:00.000
timer.CountDownFinished += () => MessageBox.Show("Timer finished the work!"); 

//timer step. By default is 1 second
timer.StepMs = 33; 

и не забудьте Dispose();, когда таймер для вас бесполезен;


Исходный код:

using System;
using System.Windows.Forms;

public class CountDownTimer : IDisposable
{
    public Action TimeChanged;
    public Action CountDownFinished;

    public bool IsRunnign => timer.Enabled;

    public int StepMs
    {
        get => timer.Interval;
        set => timer.Interval = value;
    }

    private Timer timer = new Timer();

    private DateTime _maxTime = new DateTime(1, 1, 1, 0, 30, 0);
    private DateTime _minTime = new DateTime(1, 1, 1, 0, 0, 0);

    public DateTime TimeLeft { get; private set; }
    private long TimeLeftMs => TimeLeft.Ticks / TimeSpan.TicksPerMillisecond;

    public string TimeLeftStr => TimeLeft.ToString("mm:ss");

    public string TimeLeftMsStr => TimeLeft.ToString("mm:ss.fff");

    private void TimerTick(object sender, EventArgs e)
    {
        if (TimeLeftMs > timer.Interval)
        {
            TimeLeft = TimeLeft.AddMilliseconds(-timer.Interval);
            TimeChanged?.Invoke();
        }
        else
        {
            Stop();
            TimeLeft = _minTime;

            TimeChanged?.Invoke();
            CountDownFinished?.Invoke();
        }
    }

    public CountDownTimer(int min, int sec)
    {
        SetTime(min, sec);
        Init();
    }

    public CountDownTimer(DateTime dt)
    {
        SetTime(dt);
        Init();
    }

    public CountDownTimer()
    {
        Init();
    }

    private void Init()
    {
        TimeLeft = _maxTime;

        StepMs = 1000;
        timer.Tick += new EventHandler(TimerTick);
    }

    public void SetTime(DateTime dt) {
        TimeLeft = _maxTime = dt;
        TimeChanged?.Invoke();
    }

    public void SetTime(int min, int sec=0) => SetTime(new DateTime(1, 1, 1, 0, min, sec));

    public void Start() => timer.Start();

    public void Pause() => timer.Stop();

    public void Stop()
    {
        Pause();
        Reset();
    }

    public void Reset()
    {
        TimeLeft = _maxTime;
    }

    public void Restart()
    {
        Reset();
        Start();
    }

    public  void Dispose() => timer.Dispose();
}
1 голос
/ 31 мая 2011

Вам нужно будет использовать таймер и подключиться к событию Tick, чтобы сделать то, что вы ищете.http://msdn.microsoft.com/en-us/library/system.windows.forms.timer.aspx

0 голосов
/ 16 апреля 2015

Вам нужен открытый класс для Form1 для инициализации.

См. Этот код:

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

        private int counter = 60;
        private void button1_Click(object sender, EventArgs e)
        {
            //Insert your code from before
        }

        private void timer1_Tick(object sender, EventArgs e)
        {
            //Again insert your code
        }
    }
}

Я пробовал это, и все работало нормально

Если вам нужна помощь, не стесняйтесь комментировать:)

0 голосов
/ 31 мая 2011

Как насчет использования класса Timer из .NET Framework? http://msdn.microsoft.com/en-us/library/0tcs6ww8.aspx

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...