C# winform间窗体传值简单Demo

时间:2023-03-09 03:39:37
C# winform间窗体传值简单Demo

form1是用来接收值的

C# winform间窗体传值简单Demo

 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 DelegateEventDemo
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
Form2 f2 = new Form2();
private void Form1_Load(object sender, EventArgs e)
{
this.Text = "接收值";
f2.DelegateEvent += new Form2.DelegateMessage(GetText);
}
private void GetText(string msg)
{
this.textBox1.Text = msg;
} private void button1_Click(object sender, EventArgs e)
{
f2.Show();
}
}
}

Form1代码

form2是发送值的

C# winform间窗体传值简单Demo

 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 DelegateEventDemo
{
public partial class Form2 : Form
{
public Form2()
{
InitializeComponent();
} public delegate void DelegateMessage(string txt);//声明一个委托
public event DelegateMessage DelegateEvent;//声明委事件 private void Form2_Load(object sender, EventArgs e)
{
this.Text = "传值窗体";
} private void button1_Click(object sender, EventArgs e)
{
DelegateEvent(this.textBox1.Text);
}
}
}

From2代码

1.委托是把方法当做参数一样使用

a)委托(int a,int b)

方法(int a,int b)

{

    return a+b;

}

  委托  委托对象=new 委托(方法名);

  int sum=委托对象(5,3);

  结果 sum=8;