Jairo Franchi
Jairo Franchi

Reputation: 377

Open another Form from Main Form and then close the Main Form on C# Project

I working on a C# Windows Form Project where the main form is a Login Form that I will call another Form when the Login is successfully done, but my question is, how can I set the called form as the main and then close the one created initially?

Upvotes: 0

Views: 2046

Answers (1)

Tobias J
Tobias J

Reputation: 22833

You will likely want to simply Show() the new form, and Hide() the login form.

var secondForm = new MyForm(); // or whatever the name of your form is
secondForm.Show();
this.Hide();

You could call Close() instead of Hide() on the login form, but that would end the application. You can see this in the Main method in Program.cs, which probably looks like:

    /// <summary>
    /// The main entry point for the application.
    /// </summary>
    [STAThread]
    static void Main()
    {
        Application.EnableVisualStyles();
        Application.SetCompatibleTextRenderingDefault(false);
        Application.Run(new LoginForm());
    }

Once that initial LoginForm from Application.Run closes, the program ends. You can change this by changing what Main() does (i.e. which form it opens as the initial form). For example, you could set the second form as your main form, then if the user isn't logged in, hide itself in the Form_Load event.

So depending on your workflow, it's helpful to think of these forms in terms of Show(), Hide(), and Close(). Any number of forms could exist at any time, and you simply control which ones are shown to the user depending on your workflow.

If you want to explicitly exit your application, but the initial form is hidden, you can call Application.Exit() from someplace else.

Upvotes: 2

Related Questions