Adding a form closing event to code for a specific instance of an object?

Quite simply, what I want to do, just want to be able to run the code after closing the form.

Form1 f = new Form1();
f.Show();
f.formClosing ... <- I just want to run code from this context once this form has been closed
+3
source share
4 answers
{
    Form1 f = new Form1();
    f.FormClosed += new FormClosedEventHandler(f_FormClosed);
    f.Show();
}

void f_FormClosed(object sender, FormClosedEventArgs e)
{
    // Do stuff here
}
+10
source

You can handle the Form.FormClosing event .

this.FormClosing += new FormClosingEventHandler(myForm_FormClosing);

void myForm_FormClosing(object sender, FormClosingEventArgs e)
{
    //your code here
}
+9
source

Form.FormClosing occurs before the form is closed. If you cancel this event, the form will remain open.

The correct event to handle is Form.FormClosed :

form.FormClosed += 
     new Form.FormClosedEventHandler( Place the name of the handler method here ... );
0
source

Modern line:

FormClosed += (s, a) => { /* your code here */ };
0
source

All Articles