tags:

views:

320

answers:

3

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#.

A: 

Did you try to find it out your self? http://www.dreamincode.net/forums/showtopic57482.htm

Ivo
A: 

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      
    }
  }
Maestro1024
thanx...it worked....but how i do display the countdown on the form?
knowledgehunter
+3  A: 

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();
    }
Tim
hey bro thanx a lot...it worked....actually i m a fresher in prog so i would really appreciate if u explain me how it works.especially these two lines: MyTimer.Tick += new EventHandler(MyTimer_Tick);MyTimer.Start();and why 1000??i.e in 45*60*1000....and i want to display the time(countdown) display in a label or somthn like dat on the form...thanx
knowledgehunter
MyTimer.Tick += new EventHandler(MyTimer_Tick);The timer has an event called Tick when the set interval elapses. In this case, we are saying that we want to invoke the MyTimer_Tick method when the tick event occurs.MyTimer.Interval = (45 * 60 * 1000);The interval of the timer is in milliseconds and thus I used a calculation rather than just working out the answer and sticking in the value. I think this makes it a bit easier to understand.
Tim
thanx...i got it...bt wat about displaying the countdown at the form??
knowledgehunter
If you want to display countdown then you have to use timer with higher granularity (eg. 1 second or 1 minute, depending on what you expect) and handle the logic inside it.
Filip Navara