是否可以从另一个表单触发点击事件?

l--*_*''' 11 .net c# .net-4.0 .net-3.5 winforms

我需要运行另一个表单上的按钮代码.是否可以从不同的形式做到这一点?如果你说通过宣布公开可行,那么:

  1. 我如何宣布控制公开?
  2. 我如何将正确的事件传递给button_click?它需要两个参数 - 我如何通过它们?

Dus*_*ine 15

为什么不在两个click事件都执行的共享类中创建公共方法.


Hom*_*mam 8

可以在a中进行控制Form public,但不推荐,您可以执行以下操作:

1)以第一种形式(form1)ButtonFirstFormClicked声明一个新事件

public event EventHandler ButtonFirstFormClicked;
Run Code Online (Sandbox Code Playgroud)

并在Button.Click事件处理程序中触发此事件

void button_Clicked(object sender, EventArgs e)
{

    // if you're working with c# 6.0 or greater
    ButtonFirstFormClicked?.Invoke(sender, e);

    // if you're not then comment the above method and uncomment the below
    //if (ButtonFirstFormClicked!= null)
    //     ButtonFirstFormClicked(sender, e);
}  
Run Code Online (Sandbox Code Playgroud)

2)在第二种形式(form2)中订阅事件

form1.ButtonFirstFormClicked += (s, e)
{
 // put your code here...
} 
Run Code Online (Sandbox Code Playgroud)

祝好运!