Hey

Say I have a login and the main form.
If the login window is closed then the other form shouldn't load.
I tried using a if condition to suppress initializeComponent but it still shows the main form, but empty.
How would you do that?

Dani AI

Generated

Short answer: don't construct or show the main form at all unless the login succeeds. What you saw — an empty window — happens when a Form instance exists (or its handle is created) but the control tree from InitializeComponent was never built. Suppressing InitializeComponent is fragile; instead decide whether to create the main form after the login completes.

As pointed out, run the login first and only create the main UI if authentication succeeds. A common, simple pattern is to show the login as a modal dialog and then start the main message loop only when it returns OK:

using (var login = new LoginForm())
{
    if (login.ShowDialog() == DialogResult.OK)
    {
        Application.Run(new MainForm());
    }
}

Ensure the login form sets DialogResult = DialogResult.OK (or expose a clear IsAuthenticated property) only when credentials are valid. See the docs for Form.ShowDialog and DialogResult.

If a single message loop is required (avoid calling Application.Run twice), use a custom ApplicationContext to control startup and shutdown. The context can show the login, then show the main form or call ExitThread() if login fails; this keeps lifetime management clean (see ApplicationContext).

Troubleshooting tips: do not call InitializeComponent conditionally — instead avoid creating the main form until ready; check for swallowed exceptions in the constructor; ensure the login sets a clear result; avoid multiple message loops unless you understand the side effects. These changes will prevent the empty window and make the app lifecycle explicit.

I would modify the Main method in to something like:

[STAThread]
static void Main() {
    Application.EnableVisualStyles();
    Application.SetCompatibleTextRenderingDefault(false);
    LoginForm lif = new LoginForm();
    Application.Run(lif);
    if (lif.Success) {
        Application.Run(new Form1());
    }
}

You'll need to add a property to your login form (in my example, Success) that lets you know if the user logged in.

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.