如何在Timer_tick()事件中触发Button_Click()事件? [英] How to fire Button_Click() event inside Timer_tick() event?

查看:191
本文介绍了如何在Timer_tick()事件中触发Button_Click()事件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何在.net Windows Form应用程序项目中的Timer_Tick()事件旁边触发Button_Click()事件?
这样,将根据设置的时间间隔连续执行Button_Click()中编写的代码.

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.

推荐答案

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


或:


or:

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):

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

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

private void MyMethod()
{
}


坏主意.请了解事件;并且您将看到,与常规"委托实例不同,除了声明该事件的类的实例之外,不可能从任何地方调用任何事件,您甚至无法在派生类中进行任何操作.这是有充分理由的.这是一个重要的傻瓜功能.

请查看我过去的答案:
由于我们有多播委托,所以为什么我们需要事件吗? [ ^ ],
c#联网窗口表单 [
—SA
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


通常,您会将实际代码放在另一个方法中,然后从Button_Click()调用该方法.

现在,您还可以从Timer_Tick()方法中调用该方法.
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.


这篇关于如何在Timer_tick()事件中触发Button_Click()事件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆