Add timer in a Windows Forms application using C#.

edited March 2023 in Web Development

Hello There,

To add a timer in a Windows Forms application using C#

Code:

public partial class AddTimer : AddTimer

{

public AddTimer()

{

InitializeComponent();

  Timer MyTimer = new Timer();

MyTimer.Interval = 1000;

      MyTimer.Tick += new EventHandler(MyTimer_Tick);

      MyTimer.Start();

      TestDuration = RemainingTi.Text;

}

Here is the In the Tick event handler method, you want to execute each time the timer ticks.

 private void MyTimer_Tick(object sender, EventArgs e)

    {

      TimeSpan fixedTime = TimeSpan.FromSeconds(Convert.ToDouble(TestDurationSeconds));

      TimeSpan updated = fixedTime.Add(new TimeSpan(0, 0, -1));

      TestDurationSeconds = (Int32.Parse(TestDurationSeconds) - 1).ToString();

      RemainingTi.Text = updated.ToString();

      if (Int32.Parse(TestDurationSeconds) == 0)

      {

        Debug.WriteLine("Stopped");

        MyTimer.Stop();

      }

    }

}

Thank you.

Sign In or Register to comment.