How to avoid raising an event to a closed form?
- by Steve Dignan
I'm having trouble handling the scenario whereby an event is being raised to a closed form and was hoping to get some help.
Scenario (see below code for reference):
Form1 opens Form2
Form1 subscribes to an event on Form2 (let's call the event FormAction)
Form1 is closed and Form2 remains open
Form2 raises the FormAction event
In Form1.form2_FormAction, why does this return a reference to Form1 but button1.Parent returns null? Shouldn't they both return the same reference?
If we were to omit step 3, both this and button1.Parent return the same reference.
Here's the code I'm using...
Form1:
public partial class Form1 : Form
{
public Form1 ()
{
InitializeComponent();
}
private void button1_Click ( object sender , EventArgs e )
{
// Create instance of Form2 and subscribe to the FormAction event
var form2 = new Form2();
form2.FormAction += form2_FormAction;
form2.Show();
}
private void form2_FormAction ( object o )
{
// Always returns reference to Form1
var form = this;
// If Form1 is open, button1.Parent is equal to form/this
// If Form1 is closed, button1.Parent is null
var parent = button1.Parent;
}
}
Form2:
public partial class Form2 : Form
{
public Form2 ()
{
InitializeComponent();
}
public delegate void FormActionHandler ( object o );
public event FormActionHandler FormAction = delegate { };
private void button1_Click ( object sender , EventArgs e )
{
FormAction( "Button clicked." );
}
}
Ideally, I would like to avoid raising events to closed/disposed forms (which I'm not sure is possible) or find a clean way of handling this in the caller (in this case, Form1).
Any help is appreciated.