Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Add timer to a Windows Forms application

Tags:

c#

winforms

I want to add a timer rather than a countdown which automatically starts when the form loads. Starting time should be 45 minutes and once it ends, i.e. on reaching 0 minutes, the form should terminate with a message displayed. How can I do this?

Language: preferably C#.

like image 658
knowledgehunter Avatar asked Jul 17 '09 11:07

knowledgehunter


People also ask

What is timer in Windows form?

This class provides methods to set the interval, and to start and stop the timer. The Windows Forms Timer component is single-threaded, and is limited to an accuracy of 55 milliseconds. If you require a multithreaded timer with greater accuracy, use the Timer class in the System.

How do I add a timer in Visual Studio?

Select the Toolbox tab, in the Components category, double-click or drag the Timer component to your form. The timer icon, called timer1, appears in a space below the form. Select the Timer1 icon to select the timer. In the Properties window, select the Properties button to view properties.


2 Answers

Bit more detail:

    private void Form1_Load(object sender, EventArgs e)
    {
        Timer MyTimer = new Timer();
        MyTimer.Interval = (45 * 60 * 1000); // 45 mins
        MyTimer.Tick += new EventHandler(MyTimer_Tick);
        MyTimer.Start();
    }

    private void MyTimer_Tick(object sender, EventArgs e)
    {
        MessageBox.Show("The form will now be closed.", "Time Elapsed");
        this.Close();
    }
like image 119
Tim Avatar answered Nov 08 '22 16:11

Tim


Something like this in your form main. Double click the form in the visual editor to create the form load event.

 Timer Clock=new Timer();
 Clock.Interval=2700000; // not sure if this length of time will work 
 Clock.Start();
 Clock.Tick+=new EventHandler(Timer_Tick);

Then add an event handler to do something when the timer fires.

  public void Timer_Tick(object sender,EventArgs eArgs)
  {
    if(sender==Clock)
    {
      // do something here      
    }
  }
like image 21
Maestro1024 Avatar answered Nov 08 '22 14:11

Maestro1024