While working on CamoPicker, I decided I needed to display one of two forms when the program started up, and while the program was running, allow the user to change to the other form if desired. I used a Settings
object to save the currently selected form, and treat both forms as modeless forms. That way, initialization only happens once (a requirement in my app), and the forms are easily displayed by subsequent user interaction. The necessary code bits follow. Both forms contain the same code with appropriate class name replacements where indicated.
In Program.cs, I loaded the appropriate form (saved during the last program execution).
static void Main()
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
switch (Settings1.Default.LastForm)
{
case "Form2" :
Application.Run(new Form2());
break;
default :
Application.Run(new Form1());
break;
}
}
In the form classes, I handled the Closed
event and added a method to show the form if it had already been shown once:
private void btnClose_Click(object sender, EventArgs e)
{
foreach(Form otherForm in Application.OpenForms)
{
if (otherForm is Form2)
{
otherForm.Close();
}
}
Application.Exit();
}
public void ShowAgain()
{
this.Cursor = Cursors.WaitCursor;
Settings1.Default.LastForm = "Form1";
Settings1.Default.Save();
this.Cursor = Cursors.Default;
this.Show();
}
Finally, I use a button on each form to show the other form:
private void btnShowForm2_Click(object sender, EventArgs e)
{
FormAdvanced otherForm = null;
bool formExists = false;
foreach(Form form in Application.OpenForms)
{
if (form is Form2)
{
otherForm = form as Form2;
formExists = true;
break;
}
}
if (!formExists)
{
otherForm = new Form2();
otherForm.Show();
}
else
{
otherForm.ShowAgain();
}
this.Hide();
}
The net effect is that I only have one form at a time displayed for the app, yet I can have as many different forms as necessary. In my case, I only needed two, but you might have different requirements.