[...]
If you close the main form for you application (the one created in
program.cs) the program will exit, unless you
change that code.
That's correct. Application.Run() adds a handler for the passed-in form's
Closed event, in which it calls ExitThread().
http://msdn2.microsoft.com/en-us/library/ms157902(VS.80).aspx
However, hiding the form is only an appropriate solution if you're keeping
a reference to that form and intend to show it again later. If the form
is intended to remain closed, then you really should be closing it
(allowing it to be disposed).
In this case, yes the Main() method in the Program class will need to be
modified, so that it just calls Run() without passing a form (showing the
initial form first, of course), and you'll need to add an explicit call to
Application.ExitThread() where you really want the application to be shut
down, but that's much better than being sloppy about resource management..
After you're done, it'll look something like this (leaving out the default
stuff):
static class Program
{
/// <summary>
/// The main entry point for the application.
/// </summary>
[STAThread]
static void Main()
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
new Form1().Show();
Application.Run();
}
}
public partial class Form1 : Form
{
private void button1_Click(object sender, EventArgs e)
{
Form2 form2 = new Form2();
form2.Show();
Close();
}
}
public partial class Form2 : Form
{
protected override void OnClosed(EventArgs e)
{
base.OnClosed(e);
Application.ExitThread();
}
}
Don't be afraid to edit Program.cs to suit your needs. It's generated by
the project template, but it's not part of a designer or anything. Once
it's in your project, you can always modify it as appropriate.
Pete