//Form1
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
namespace TestDelegates1
{
public delegate void MyDelegate(string msg);
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
new Form2().Show();
}
public void ShowMsg(string msg)
{
textBox1.Text = msg;
MessageBox.Show(msg);
}
}
}
///Form2
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
namespace TestDelegates1
{
public partial class Form2 : Form
{
public Form2()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
Form1 frm1 = new Form1();
MyDelegate dg = new MyDelegate(frm1.ShowMsg);
dg("Hello");
}
}
}
//Form1
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
namespace TestDelegates1
{
public delegate void MyDelegate(string msg);
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
new Form2(this).Show();
}
public void ShowMsg(string msg)
{
textBox1.Text = msg;
}
}
}
///Form2
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
namespace TestDelegates1
{
public partial class Form2 : Form
{
private Form1 frm1;
public Form2(Form1 f)
{
InitializeComponent();
frm1 = f;
}
private void button1_Click(object sender, EventArgs e)
{
MyDelegate dg = new MyDelegate(frm1.ShowMsg);
dg("Hello");
}
}
}
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
Form2 f2 = new Form2();
f2.OnShowMsg += new Form2.MyDelegate(f2_OnShowMsg);
f2.Show();
}
void f2_OnShowMsg(string msg)
{
MessageBox.Show(msg);
}
}
ที่ form 2 Code (C#)
public partial class Form2 : Form
{
public delegate void MyDelegate(string msg);
public event MyDelegate OnShowMsg;
public Form2()
{
InitializeComponent();
Load += new EventHandler(Form2_Load);
}
void Form2_Load(object sender, EventArgs e)
{
OnShowMsg("Form2_Load");
}
}