用委托来实现子窗体操作父窗体中的控件
代码实现
Form1中,一个Lable1;在Form2中控制Form1中的Lable1的显示或隐藏!
Form1代码:
-
view plaincopy to clipboardprint?
- namespace WindowsApplication2
- {
- public delegate void SetVisiableHandler();
- public partial class Form1 : Form
- {
- public Form1()
- {
- InitializeComponent();
- }
- private void button1_Click(object sender, EventArgs e)
- {
- Form2 frm = new Form2(new SetVisiableHandler(SetVisiable));
- frm.Show();
- }
- private void SetVisiable()
- {
- SetVisiable(this.label1, !this.label1.Visible);
- }
- private void SetVisiable(Control control, bool visiable)
- {
- if (this.Controls.Contains(control))
- {
- control.Visible = visiable;
- }
- }
- }
- }
namespace WindowsApplication2 { public delegate void SetVisiableHandler(); public partial class Form1 : Form { public Form1() { InitializeComponent(); } private void button1_Click(object sender, EventArgs e) { Form2 frm = new Form2(new SetVisiableHandler(SetVisiable)); frm.Show(); } private void SetVisiable() { SetVisiable(this.label1, !this.label1.Visible); } private void SetVisiable(Control control, bool visiable) { if (this.Controls.Contains(control)) { control.Visible = visiable; } } } }
- Form2代码
view plaincopy to clipboardprint?
- namespace WindowsApplication2
- {
- public partial class Form2 : Form {
- private SetVisiableHandler m_setVisible;
- public Form2(SetVisiableHandler setvisible)
- {
- InitializeComponent();
- this.m_setVisible = setvisible;
- }
- private void btnVisible_Click(object sender, EventArgs e)
- {
- if (this.m_setVisible != null)
- {
- this.m_setVisible();
- }
- }
- }
- }