Click here to Skip to main content
15,887,328 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
How to fire Button_Click() event in side the Timer_Tick() event in .net windows form application project?
So that what are codes written in Button_Click() will be executed continuously according time interval set.
Posted
Updated 14-Jun-12 20:27pm
v3
Comments
Sergey Alexandrovich Kryukov 15-Jun-12 1:59am    
I wonder why...
--SA

C#
private void timer1_Tick(object sender, EventArgs e)
{
   button1.PerformClick();
}

or:
C#
private void timer1_Tick(object sender, EventArgs e)
{
   button1_Click(button1, null);
}

private void button1_Click(object sender, EventArgs e)
{
}

or (this is the preferred solution):
C#
private void timer1_Tick(object sender, EventArgs e)
{
   MyMethod();
}

private void button1_Click(object sender, EventArgs e)
{
   MyMethod();
}

private void MyMethod()
{
}
 
Share this answer
 
Comments
Amund Gjersøe 15-Jun-12 2:52am    
As Click-handlers usually are running in the GUI thread, and the timer in the thread pool, you should consider testing for InvokeRequired in the button1_Click.
JF2015 15-Jun-12 2:57am    
In this case I would use the System.Windows.Forms.Timer
Bad idea. Please, learn about events; and you will see, that, unlike "regular" delegate instances, it is not possible to invoke any event from anywhere except the instance of the class where the event is declared, you cannot even do it in a derived class. And this is done for a good reason; this is an important fool-proof feature.

Please see my past answers:
Since we have multicast delegates, why do we need events?[^],
c# networking windows form[^].

In practice, such thing is never needed. In the second answer referenced above, I explain what to do. You don't really want to fire the event; as you say yourself, you need to execute "code written in…" where? — in the code of event handler. Nothing prevents you to do it; and it has nothing to do with event invocation.

—SA
 
Share this answer
 
Usually, you would put the actual code in another method and call that method from Button_Click().

Now you can also call that method from your Timer_Tick() method.
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900