Well that's going to depend heavily on how you are interacting with the revit api. Are you doing ALL logic in the form class or do you have separate classes for accessing the api?
Regardless, you need to add an event handler to the Form.FormClosing event. Something like:
//Put this line in your form constructor
this.FormClosing += CloseAllTheThings;
void CloseAllTheThings(object sender, EventArgs e)
{
//Close and release stuff
}