弗瑞斯达

  博客园 :: 首页 :: 博问 :: 闪存 :: 新随笔 :: 联系 :: :: 管理 ::

理解委托:关于两个窗体的互操作

 

Form1:

    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void frm_setTextEvent(string text)
        {
            this.Text = text;
        }

        private void button1_Click(object sender, EventArgs e)
        {
            Form2 frm = new Form2();
            frm.setTextEvent += new Form2.setTextHandler(frm_setTextEvent);
            frm.Show();
        }
    }

 

Form2:

    public partial class Form2 : Form
    {
        public delegate void setTextHandler(string text);
        public event setTextHandler setTextEvent;

        public Form2()
        {
            InitializeComponent();
            this.button1.Click += new EventHandler(button1_Click);
        }

        private void button1_Click(object sender, EventArgs e)
        {
            if (setTextEvent != null)
            {
                setTextEvent("yourtext");
            }
        }
    }

 

 

 

posted on 2010-10-20 23:36  弗瑞斯达  阅读(172)  评论(0编辑  收藏  举报