Cocoa Dev
Cocoa Dev

Reputation: 9541

C# Window is immediately closing after creating it

Form1 browser = new Form1(textBoxUserName.Text.Trim(), textBoxOldPassword.Text.Trim(), textBoxNewPassword.Text.Trim());
browser.Shown += (o, t) => { this.Close(); }; 
browser.Show(); 

I want the new Window to show up and the old window to close.

What's happening is that the application is being shutdown automatically when the this.Close() is being called

I am using WinForms

Upvotes: 2

Views: 676

Answers (2)

Leonardo
Leonardo

Reputation: 2225

I assume that your code is from your main form ParentForm and the message pump was started by

Application.Run(new ParentForm());

which ends when ParentForm is closed. To achieve what you're trying to do you can rather write:

[STAThread]
static void Main()
{
    Form form = new ParentForm();
    form.Show();

    Application.Run(); // starts the message pump
}

In this case you must explicitly call Application.Exit() to end your program, e.g.

public class Form1 : Form
{
    protected override void OnClosed(EventArgs e)
    {
        base.OnClosed();

        Application.Exit();
    }
}

A more clean approach would make use of ApplicationContext.

Upvotes: 2

Pushpendra
Pushpendra

Reputation: 810

If your this is the first form from where your application is getting loaded and if you close it, the application will close.

Instead of this.Close()

Do write it as this.Hide().

Upvotes: 0

Related Questions