How can I add an event or some whey to know in any class I use the timer to know when the timer reached the count time ?

rhodanny 166 Reputation points
2021-11-14T15:32:58.15+00:00

The timer class

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

namespace Extract
{
    public partial class TimeCounter : Label
    {
        private bool CountUp { get; set; }
        private int TimeToCount = 300;
        private int Interval = 1000;
        private Timer _timer;
        private TimeSpan ts;

        public TimeCounter()
        {
            InitializeComponent();

            ts = TimeSpan.FromSeconds(TimeToCount);

            StartCountDownTimer(TimeToCount, Interval, CountUp, false);
        }

        public void StartCountDownTimer(int TimeToCount, int Interval,
            bool CountUp, bool EnableTimer)
        {
            _timer = new Timer
            {
                Interval = Interval,
                Enabled = false
            };

            _timer.Enabled = EnableTimer;

            _timer.Tick += (sender, args) =>
            {
                if(ts == TimeSpan.FromSeconds(0))
                {
                    ts = TimeSpan.FromSeconds(TimeToCount);
                }

                if (CountUp)
                {
                    ts = ts.Add(TimeSpan.FromSeconds(1));
                }
                else
                {
                    ts = ts.Subtract(TimeSpan.FromSeconds(1));
                }

                this.Text = ts.ToString();
            };
        }

        private void TimeCounter_Load(object sender, EventArgs e)
        {

        }
    }
}

I drag the control to form1 designer and then using the method StartCountDownTimer when ever I want to start the counter at any place and time.

The problem is how do I know when the counter for example get to 00:00:00 and then to do something for example in form1 ? or if the timer get to 04.06.22 or any time I set it to count to.
I need a way to find how to do something easy when the counter reached the time to count.

Windows Forms
Windows Forms
A set of .NET Framework managed libraries for developing graphical user interfaces.
1,922 questions
C#
C#
An object-oriented and type-safe programming language that has its roots in the C family of languages and includes support for component-oriented programming.
11,294 questions
{count} votes

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.