0

Possible Duplicate:
How do I prevent the app from terminating when I close the startup form?

Imagine an application with 2 forms, Form1 and Form2. When I click on a button in Form1 i want to open Form2 and close Form1, close not hide. The way I was doing it was:

_Form2 = new Form2();
_Form2.Show();
 this.Close();//or this.Dispose();

When I run the code it closes the form1 and ends the application. Im not sure but it maybe because in my Program.cs I have Application.Run(new Form1());? Or this line only means that when the Application start it should load the Form1?

Community
  • 1
  • 1
freedowz
  • 92
  • 1
  • 2
  • 11

3 Answers3

4

There are various ways to achieve what you want....it all depends on the subtle interaction you need between Form1 and Form2 and how you want to organize the sequence.

One way is to use Application.Run() instead....but you must use Application.Exit() when you want to close your application....because you need to signal that the message loop and your application should be exited.

Note this is in addition to any "form closing" calls (i.e. .Close()) that you do on a Form when you deem it no longer to be shown.

That will then allow you to show Form1 initially....(because you use the modeless Show()).....then you can close the Form1 and create and show the secondary Form2.....then do Application.Exit();

The more complicationed example in MSDN, namely Application.Run(ApplicationContext) with a context is if you have a use case where you want to have multiple forms and then want it to exit when they both are closed.

Colin Smith
  • 12,375
  • 4
  • 39
  • 47
3

Yes, you are right. The form mentioned in Run method is "the main form", if you close it you will close the application. If you want to close Form1, you can do the following:

Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault(false);
            Form1 form = new Form1();
            form.Show();
            Application.Run();

And the code to close Form1 and open Form2 on the button click:

public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void button1_Click(object sender, EventArgs e)
        {
            this.Close();
            Form2 form = new Form2();
            form.Show();
        }
    }

To exit from the app just put one more button (or provide the event handler) and run this code:

Application.Exit();
Kath
  • 1,834
  • 15
  • 17
1

If you just need a sequence of forms, you can have the main thread take care of that sequence.

So in main, you'd have:

static void Main()
{
    Application.EnableVisualStyles();
    Application.SetCompatibleTextRenderingDefault(false);
    Application.Run(new Form1());
    Application.Run(new Form2());
}

And all you need to do is close Form1 for it to continue to the next one:

private void button1_Click(object sender, EventArgs e)
{
    this.Close();
}
Skorov
  • 11
  • 1