实现步骤:
1.创建窗体Form1和Form2
2.在窗体1中添加一个按钮(Button)和文本框(TextBox)控件,窗体2添加文本框
3.窗体1的按钮中点击事件中,加入窗体2对象并打开
4.添加一个方法(ChangeTxtBox)用于更改Form1的文本框
5.声明一个带参数的委托(MyDelegate),委托变量(ChangeDel)
6.按钮中加入委托用于Form2传给Form1的值
实现细节:
Form1:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace 使用委托进行窗体间传值
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
Form2 f2 = new Form2();
f2.ChangeDel = new MyDelegate(this.ChangeTxtBox);
f2.Show();
}
private void ChangeTxtBox(string msg)
{
this.textBox1.Text = msg;//更改Form1的文本框
}
private void textBox1_TextChanged(object sender, EventArgs e)
{
}
}
}
Form2:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace 使用委托进行窗体间传值
{
public partial class Form2 : Form
{
public MyDelegate ChangeDel { get; set; }
public Form2()
{
InitializeComponent();
}
private void textBox1_KeyUp(object sender, KeyEventArgs e)
{
string txt = this.textBox1.Text;//获取当前文本框的值
if (ChangeDel != null)
{
ChangeDel.Invoke(txt);
}
}
}
}
创建的委托
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace 使用委托进行窗体间传值
{
public delegate void MyDelegate(string msg);
}
效果: