在C#中使用委托

来源:互联网 发布:打开dll的软件 编辑:程序博客网 时间:2024/05/17 04:39
要求如下:在窗体Form1、Form2中各有一个文本框、一个按钮,现在我需要点击Form1中的按钮,弹出窗体Form2,然后在窗体Form2中的文本框中输入字符串,然后点击Form2中的按钮,将文本框中的值传到Form1中的文本框中。【第一种方法:】窗体Form2中的代码如下:        public delegate void SendDate(object sender);        public SendDate sendDate;        private void button1_Click(object sender, EventArgs e)        {            if (sendDate != null) {                sendDate(rtxtValue.Text);//注意:在这里还可以传入一个控件,比如:sendDate(rtxtValue)            }            this.Close();        }窗体Form1中的代码如下: private void button1_Click(object sender, EventArgs e)         {            Form4 f = new Form4();            f.sendDate = new Form4.SendDate(Funcation);            f.ShowDialog();         }         private void Funcation(object sender)         {            this.textBox1.Text = sender.ToString();   //this.textBox1.Text=((TextBox)sender).Text;         }【第二种方法:】Form2:public delegate void SendMsg(string msg);private void button1_Click(object sender, EventArgs e)        {            Form1 f = new Form1();            SendMsg sm = new SendMsg(f.getMsg);           sm(textBox1.Text);            this.Close();}Form1:   public void getMsg(string msg)        {                     MessageBox.Show(msg);       }        private void button1_Click(object sender, EventArgs e)        {            Form2 f = new Form2();                   f.Show();        }