110,567
社区成员
发帖
与我相关
我的任务
分享
namespace WindowsFormsApplication1
{
public partial class Form1 : Form
{
FireButtonClickDelegate m_delegate;
Button m_btnInChild;
public Button BtnInChild
{
get { return m_btnInChild; }
set { m_btnInChild = value; }
}
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
Form2 frm = new Form2();
frm.MdiParent = this;
frm.Show();
}
private void button2_Click(object sender, EventArgs e)
{
//用委托
//m_delegate = new FireButtonClickDelegate(ShowMessage);
//this.Invoke(m_delegate);//执行子窗体中方法
//直接用button
this.InvokeOnClick(m_btnInChild, null);//点击子窗体的button
}
public FireButtonClickDelegate Delegate
{
set
{
m_delegate = value;
}
}
private void ShowMessage()
{
MessageBox.Show("Called from delegate!");
}
}
public delegate void FireButtonClickDelegate();
}
public partial class Form2 : Form
{
public Form2()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
ShowMessage();
}
private void ShowMessage()
{
MessageBox.Show("I was clicked!", "Haha");
}
private void Form2_Activated(object sender, EventArgs e)
{
Form1 mainForm = (Form1)this.MdiParent;
//用委托
mainForm.Delegate = new FireButtonClickDelegate(ShowMessage);//用委托的方式告诉主窗体要执行的方法
//不用委托
mainForm.BtnInChild = button1;//直接告诉主窗体要点击哪个button
}
}
frm.button1_Click(frm.button1, null);