tags:

views:

297

answers:

4

Hi, 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)
{ 
}

Thanks in advacne Madhu

A: 

You might try removing the handler rather than disabling the Timer

mytimer.Tick -= new System.EventHandler(timer1_Tick);
Hugoware
Thank you. That works.
Madhu kiran
+4  A: 
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.

BFree
If you don't specifically _need_ the timer for anything, this is the way to go.
AllenG
+1  A: 

Probably nothing to do with it, but I would set the timer enabled after I set EventHandler. (This has caused grief in a previous project where more code was inserted between the two statements later on.)

dverespey
+7  A: 

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.

AllenG
Good eyes there man - Didn't notice that
Hugoware
Good one, missed it too.
dverespey