I See Sharp I See Sharp - 9 months ago 75
Vb.net Question

How to handle on close event of a programmatically created Form in VB.NET?

I am new to VB.NET and I'm stuck with the following:

I want to perform some operations before a programmatically-created Form closes.

I need to handle the Close event of my Form (created in code).

How can I do this?

Below is how they do it with C#

Form1 f = new Form1();
f.FormClosed += new FormClosedEventHandler(f_FormClosed);

void f_FormClosed(object sender, FormClosedEventArgs e)
// Do stuff here


In VB.NET events are handled a little bit differently. If you want to use the Handles clause in addition to the form's FormClosed delegate declaration, you need to declare the object (Form in your case) with the WithEvents key word at a module level:

Private WithEvents frmX AS New Form

Then you can just write:

Private Sub frmX_FormClosed(sender As Object, e As FormClosedEventArgs) Handles frmX.FormClosed

End Sub

The compiler will then take care of attaching and detaching the handler as appropriate.

If you want to take control yourself, then declare the Form wherever you'd like and use the AddHandler and RemoveHandler directives as appropriate:

// Define the handler delegate as usual:
Private Sub frmX_FormClosed(sender As Object, e As FormClosedEventArgs)

End Sub

// Somewhere else in your code use this:

// To attach the handler:
AddHandler frmX.FormClosed, AddressOf Form5_FormClosed

// To detach the handler:
RemoveHandler frmX.FormClosed, AddressOf frmX_FormClosed

The .FormClosed will popup in the AddHandler / RemoveHandler context. Note the AddressOf keyword. It is mandatory when you need to specify a delegate.