如何从另一个表单触发按钮的事件 [英] how to fire an event for a button from another form

查看:71
本文介绍了如何从另一个表单触发按钮的事件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何从其他控件中触发按钮的点击事件



需要帮助

how to fire click event for a button from a nother control

neeed help

推荐答案

以非常粗糙的方式,您可以像任何方法一样调用原始事件处理程序。敌人,例如我也从复选框中调用按钮点击事件:



In a very crude way, you can just call the original event handler just like any method. Foe e.g. I am calling the button clicked event also from checkbox changed:

private void button1_Click(object sender, EventArgs e)
{
    MessageBox.Show("Button Clicked!!!");
}

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





然而,更好的方法是回头看看你真正想要的是什么。也许你可以实现一个新的公共自定义事件,可以通过多个控件触发。



However, a better way would be look back and see what you actually want. And perhaps you can implement a new common custom event which can fired by multiple controls.


你可以这样做 - 每个按钮都有一个 PerformClick方法 [ ^ ]你可以打电话,这是相当于用鼠标点击它 - buit我会说它通常是糟糕的设计使用它,特别是来自实际的UserControl或包含按钮的Form之外 - 它将两个类锁定在一起所以你不能改变一个不考虑对另一方的影响,并且测量你必须公开,这是违反OOP原则的。



更好的方法是在其中创建方法Form / UserControl是公共的,可以由外部世界调用,它也是相同的点击按钮的事情。这样,按钮可以用不同的控件替换,而外界不需要知道它。
You can do it - each button has a PerformClick method[^] you can call, which is the equivalent of clicking it with the mouse - buit I'd say it is generally poor design to use it, particularly from outside the actual UserControl or Form that houses the button - it "locks" the two classes together so you can't change one without considering the effects on the other, and it measn you have to make teh button public, which is against OOPs principles.

A better way is to create a method within the Form / UserControl with is public and which can be called by the outside world which does the same thing as clicking the button. That way the button can be replaced with a different control without the outside world needing to know about it.


另一种方式,创建一个公共方法



Another way, create a public method

//Form1

public void SimulateClick()
{
    button1_Click(null, null);
}



//Form2

form1.SimulateClick();


这篇关于如何从另一个表单触发按钮的事件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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