我需要运行另一个表单上的按钮代码,从不同的表单中是否可能执行?如果您说通过声明它为公共,则:
- 如何声明公共控件?
- 如何传递正确的事件到
button_click? 它需要两个参数-我如何传递它们?
click
事件都可以执行该方法。可以在Form
中将控件设置为public
,但不建议这样做,您可以采取以下步骤:
1)在第一个表单(form1)中声明一个新事件ButtonFirstFormClicked。
public event EventHandler ButtonFirstFormClicked;
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);
}
2) 在第二个表单(form2)中订阅事件
form1.ButtonFirstFormClicked += (s, e)
{
// put your code here...
}
祝你好运!
你可以使用internal关键字作为修饰符,这样你就可以轻松地访问点击事件。
例如,在Form1中有一个点击事件。不要将其设置为私有的、公共的或受保护的,而是将其设置为internal。这样,你就可以在其他类中轻松地访问该方法。但是,internal修饰符只能在当前程序包中访问。(参见此处)
Form1
internal passobj;
internal passeargs;
internal void button1_Click(object obj, EventArgs e)
{
this.passobj = obj;
this.passeargs = e;
MessageBox.Show("Clicked!")
}
Form2
private void button1_Click(object obj, EventArgs e)
{
Form1 f1 = new Form1();
f1.button1_Click(f1.passobj, f1.passeargs);
}
btnMyButton.Click += new EventHandler(firstForm.MethodThatHasCodeToRun);
您可以通过在窗体设计器中更改“Modifiers”伪属性将控件设置为公共。
一旦按钮变为公共,您可以通过调用PerformClick
方法来运行它的Click
事件,例如:form1.button1.PerformClick()
。您不必直接调用事件处理程序。
但是,像Dustin Laine所建议的那样创建一个公共方法可能是更好的选择。