WinForms从另一个表单中引发事件

我有一个名为MainForm的主窗体和一个名为ChildForm的子窗体我希望填充ChildForm的文本框,在MainForm_ButtonClick中我要激活ChildForm_ButtonClick事件。

ChildForm:

public partial class ChildForm :Form { public delegate void delPassData(TextEdit text); private void button1_Click(object sender, EventArgs e) { string depart = ""; MainForm mfrm = new MainForm(); delPassData del = new delPassData(frm.funData); del(this.Item_CodeTextEdit); } } 

的MainForm:

 public partial class MainForm : Form { public void funData(TextEdit txtForm1) { string ss = ""; ss = txtForm1.Text; MessageBox.Show(ss); } private void NavigationPanelBtns_ButtonClick(object sender, ButtonEventArgs e) { switch (e.Button.Properties.Caption) { case "Save": // i want to call funData() here but i get an empty messageBox break; } } 

}

儿童forms

 public partial class ChildForm : Form { public ChildForm() { InitializeComponent(); MainForm.OnChildTextChanged += MainForm_OnChildTextChanged; MainForm.OnButtonClick += MainForm_OnButtonClick; bttn1.Visible = false; } void MainForm_OnButtonClick(object sender, EventArgs e) { this.bttn1.PerformClick(); } void MainForm_OnChildTextChanged(string value) { this.textBox1.Text = value; } private void bttn1_Click(object sender, EventArgs e) { MessageBox.Show("I am hide. But shows message"); } } public class Bttn : Button { public new void PerformClick() { this.OnClick(EventArgs.Empty); } } 

创建父表单

 public partial class MainForm : Form { public delegate void OnMyTextChanged(string value); public delegate void ButtonClicked(object sender, EventArgs e); public static event OnMyTextChanged OnChildTextChanged; public static event ButtonClicked OnButtonClick; ChildForm frm = new ChildForm(); public MainForm() { InitializeComponent(); frm.Show(); } public void button1_Click(object sender, EventArgs e) { OnChildTextChanged("this is new value"); OnButtonClick(sender, e); } } 

要以其他forms访问文本框:

  1. 将子文本框中的文本框的Modifier属性设置为public

  2. 在主窗体中,通过子窗体的对象访问文本框。

    例如:

     obj.txtBox.Text="MyValue"; 

要以其他forms访问活动:

  1. 将事件处理function设置为public

  2. 通过表单对象传递null作为参数来调用该函数。

    例如:

     obj.MyButton_Click(null, null);