Example of communication between forms of the C program using callback events
- 2020-05-24 06:04:05
- OfStack
Form2:
// define 1 A need to string The delegate of the type parameter
publicdelegate void MyDelegate(string text);
public partial class Form2 :Form1
{
// The event that defines the delegate
public event MyDelegate MyEvent;
public Form2(string text)
{
InitializeComponent();
this.textBox1.Text = text;
}
private void btnChange_Click(object sender, EventArgs e)
{
// Triggers an event and sends the modified text back
MyEvent(this.textBox1.Text);
this.Close();
}
}
Form1:
public partial class Form1 :Form
{
public int index = 0;
public string text = null;
public Form1()
{
InitializeComponent();
}
private void listBox1_SelectedIndexChanged(object sender, EventArgse)
{
if (this.listBox1.SelectedItem != null)
{
text = this.listBox1.SelectedItem.ToString();
index = this.listBox1.SelectedIndex;
Form2 form2 = new Form2(text);
// registered form2_MyEvent methods MyEvent The event
form2.MyEvent += new MyDelegate(form2_MyEvent);
form2.Show();
}
}
// To deal with
void form2_MyEvent(string text)
{
this.listBox1.Items.RemoveAt(index);
this.listBox1.Items.Insert(index, text);
}
}