This will close ALL of the forms, except the mainform (if it's already open). It also takes into account the possibility that the form that's currently running this code may NOT be the last form in the list.
int baseIndex = 0;
int thisFormIndex = -1;
while (Application.OpenForms.Count > 1)
{
if (Application.OpenForms[baseIndex] is MainForm || Application.OpenForms[baseIndex].Equals(this))
{
if (Application.OpenForms[baseIndex].Equals(this))
{
thisFormIndex = baseIndex;
}
baseIndex++;
}
else
{
Application.OpenForms[baseIndex].Close();
}
if (Application.OpenForms.Count == 2 && thisFormIndex >= 0)
{
break;
}
}
if (thisFormIndex >= 0)
{
Application.OpenForms[thisFormIndex].Close();
}
I typed this off the top of my head, so the code may need some tweaking, but you should have an idea of what I was going for.
In the end, this is a crap design, and the desired processing should actually be handled by a combination of semaphores and events so that each preceding form can determine on its own whether or not it should close based on how the child form it's monitoring closed.
EDIT ======================
You can open the main form by simply doing this:
mainForm form = new MainForm();
form.ShowDialog();
Your design still sucks. Read the last paragraph of my original answer. Read it as many times as it takes for you to understand it.