using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace delegateSend
{
public class WarnEventArgs : EventArgs
{
private string _text = String.Empty;
public string Text
{
get { return _text; }
set { _text = value; }
}
}
}
Form2给Form1传参数
Form2上放一个Textbox用于设置要传给Form1的参数,button2将参数放到WarnEventArgs的对象e中
Form1上放一个lable用于显示Form2传来的参数,button2将参数从WarnEventArgs的对象e中取出
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 delegateSend
{
public delegate void WarnDelegate(WarnEventArgs e);
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
public void Alarm(WarnEventArgs e)
{
string tem = e.Text;
label1.Text = tem.ToString();
}
private void button1_Click(object sender, EventArgs e)
{
Form2 f2 = new Form2();
f2.Show();
f2.WarnEvent += new WarnDelegate(Alarm);
}
}
}
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 delegateSend
{
public partial class Form2 : Form
{
public event WarnDelegate WarnEvent;
public Form2()
{
InitializeComponent();
}
public void OnWarnEvent(WarnEventArgs e)
{
if (WarnEvent != null)
{
WarnEvent(e);
}
}
public void Warn(string x)
{
WarnEventArgs e = new WarnEventArgs();
e.Text = x;
OnWarnEvent(e);
}
private void button1_Click(object sender, EventArgs e)
{
Warn(this.textBox1.Text);
}
}
}