Guys i have a main form. When this one is loaded it first has to show another form. So there opens a new form and the main form is hided. How can I do this?

Dani AI

Generated

Quick summary for : 's short approach will work for trivial cases, and 's tutorial shows how to return to the main form when the second closes. For more robust behavior there are two recommended patterns: show the secondary form before the main form is created (ideal for login/splash), or show it as a modal from the main form's Shown event (avoid doing UI dialog work in Load). Also be explicit about application lifetime: Application.Run ties the process to the "main" form unless you use an ApplicationContext.

Show the secondary form before starting the main form (good for login/splash):

[STAThread]
static void Main()
{
    Application.EnableVisualStyles();
    Application.SetCompatibleTextRenderingDefault(false);

    using (var login = new LoginForm())
    {
        if (login.ShowDialog() != DialogResult.OK)
            return; // cancel startup
    }

    Application.Run(new MainForm());
}

If the main form must be created first, invoke the dialog after the form is visible (prevents reentrancy/layout issues):

private void MainForm_Shown(object sender, EventArgs e)
{
    this.BeginInvoke((Action)(() =>
    {
        using (var dlg = new LoginForm())
        {
            if (dlg.ShowDialog(this) != DialogResult.OK)
                this.Close(); // stop app if login failed
        }
    }));
}

Practical notes: use ShowDialog when you want the secondary form to block until a result is known and return a DialogResult; set the owner (ShowDialog(this)) so modality and activation work correctly. If you use non-modal Show you must handle FormClosed to re-show or dispose forms. For fine-grained lifetime control (multiple entry points, hidden main window, or complex startup/shutdown logic) consider using an ApplicationContext instead of relying on a hidden main form. Official docs: Form.Shown (https://learn.microsoft.com/en-us/dotnet/api/system.windows.forms.form.shown?view=netframework-4.8), Form.ShowDialog (https://learn.microsoft.com/en-us/dotnet/api/system.windows.forms.form.showdialog?view=netframework-4.8) and Application.Run (https://learn.microsoft.com/en-us/dotnet/api/system.windows.forms.application.run?view=netframework-4.8).

Recommended Answers

All 2 Replies

Hello there,
What you could do is, on the FormLoad() Event, you could write the following code:

Form1 secForm = new Form1(); //this is the new form that you want to show.
secForm.Show();

this.Hide();

Hope i helped,
Alex

To expand on what Alexpap said check out my tutorial. It shows how to hide and then recall the current form when the second form is closed.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.