委托应用

来源:互联网 发布:华为 python 编辑:程序博客网 时间:2024/05/16 05:21

//点击按钮弹出Form2,在Form2中的textBox中输入字符时,Form1中的textBox也会显示相应的字符

Form1:

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
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.Fangfa = UpdateTextBox;
f2.Show();
}
private void UpdateTextBox(string txt)
{
this.textBox1.Text = txt;
}
}
}

Form2:

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;

namespace 委托应用

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

public WeiTuoDelegate Fangfa;//这时存储方法的一个变量

private void textBox1_KeyUp(object sender, KeyEventArgs e)
{
this.Text = this.textBox1.Text;
string userInput = this.textBox1.Text;
//希望在这里调用UpdateTextBox那个方法

//UpdateTextBox();
if (Fangfa != null)
{
Fangfa(userInput);
}

}
}
}

WT:(方法)

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace 委托应用

{
public delegate void WeiTuoDelegate(string msg);
}

原创粉丝点击