运行结果如下:
实现部分;创建两个form窗体,Form1,Form2;创建一个类MyEventArg.cs.
MyEventArg.cs代码:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace weituo
{
public class MyEventArg:EventArgs
{
public string Text { get; set; }
public string Name { get; set; }
}
}
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 weituo
{
public partial class Form1 : Form
{
#region
public event EventHandler SendMsgEvent;//使用默认的事件使用委托
#endregion
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
/* #region
Form2 form2 = new Form2();
SendMsgEvent += form2.MainFormTxtChaned;
form2.Show();
this.Hide();
#endregion*/
}
private void button1_Click(object sender, EventArgs e)
{
Form2 form2 = new Form2();
SendMsgEvent += form2.MainFormTxtChaned;
form2.Show();
// this.Hide();
SendMsgEvent(this, new MyEventArg() { Text = this.textBox1.Text, Name=this.textBox2.Text });
}
}
}
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 weituo
{
public partial class Form2 : Form
{
public void SetText(string txt,string name)
{
this.textBox1.Text = txt;
this.textBox2.Text = name;
}
public Form2()
{
InitializeComponent();
}
private void Form2_Load(object sender, EventArgs e)
{
}
internal void MainFormTxtChaned(object sender,EventArgs e)
{
MyEventArg arg = e as MyEventArg;
this.SetText(arg.Text, arg.Name);
}
}
}