Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to make a timer fire only one time

Tags:

c#

.net

timer

I am using C#2.0 and working on Winforms. I have two applications(app1,app2). when the app1 runs it will automatically invoke the app2. I have a timer in my app2 and in timer_tick I activate a buttonclick event.But I want this Button Click to be fired only one time when the app is started.

The problem i am facing is for some unknow reason the timer gets fired more than one time even though i make mytimer.Enable= false. Is there a way where i can make timer not be invoked second time. OR Is there a way i can make Button click event fired automatically without using timers.

Here is the code:

private void Form1_Activated(object sender, EventArgs e)
{
    mytimer.Interval = 2000;
    mytimer.Enabled = true;
    mytimer.Tick += new System.EventHandler(timer1_Tick);

}
private void timer1_Tick(object sender, EventArgs e)
{
    mytimer.Enabled = false;
    button1_Click(this, EventArgs.Empty);
}


private void button1_Click(object sender, EventArgs e)
{ 
}
like image 205
Madhu kiran Avatar asked Jun 11 '09 18:06

Madhu kiran


People also ask

How do I stop a timer elapsed event?

It will fire at the elapsed time. To avoid this happening set Timer. AutoReset to false and start the timer back in the elapsed handler if you need one. Setting AutoReset false makes timer to fire only once, so in order to get timer fired on interval manually start timer again.

Which event is fire after every interval of the timer?

Elapsed event is fired for the first time only after the interval time has passed.

What is System timers timer?

The Timer component is a server-based timer that raises an Elapsed event in your application after the number of milliseconds in the Interval property has elapsed. You can configure the Timer object to raise the event just once or repeatedly using the AutoReset property.


2 Answers

I haven't tested this, yet (so be ready for an edit), but I suspect because you're enabling the timer (mytimer.Enabled = true;) in the Form1_Activated event instead of when the form initially loads. So every time the the Form becomes active, it resets Enables your timer.

EDIT: Okay, I have now verified: Assuming you do actually need the timer, move the mytimer.Enabled into the form's constructor.

like image 129
AllenG Avatar answered Oct 08 '22 17:10

AllenG


public Form1 : Form()
{
   InitializeComponent();
   this.Load+= (o,e)=>{ this.button1.PerformClick();}
}

public void button1_Click(object sender, EventArgs e)
{
   //do what you gotta do
}

No need to use a timer. Just "click" the button when the form loads.

like image 41
BFree Avatar answered Oct 08 '22 17:10

BFree