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)
{
}
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.
Elapsed event is fired for the first time only after the interval time has passed.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With