Home >Backend Development >C++ >How to Show the Main Form After Successful Login in a Windows Forms Application Without Closing the App?

How to Show the Main Form After Successful Login in a Windows Forms Application Without Closing the App?

Linda Hamilton
Linda HamiltonOriginal
2025-01-10 07:01:44206browse

How to Show the Main Form After Successful Login in a Windows Forms Application Without Closing the App?

Show the main form after successful login without exiting the application

In Windows Forms applications, closing the main form usually terminates the program. However, in some cases, you may need to close the login form and launch the main form without ending the application. This article explores this problem and provides a solution.

Question:

A user creates a Windows Forms project that contains two forms: a login form and a main form. After successful login, the goal is to close the login form and display the main form. However, closing the login form using the Close() method does not open the main form, and the application terminates.

<code class="language-c#">public void ShowMain()
{
    if (auth())
    {
        var main = new Main();
        main.Show();
        this.Close();
    }
    else
    {
        MessageBox.Show("Invalid login details.");
    }
}</code>

Solution:

The problem is that closing the login form also closes the application. The solution involves moving the login logic from the login form to the Program.cs file. Then, launch the main form after a successful login by using Application.Run().

<code class="language-c#">static void Main()
{
    LoginForm fLogin = new LoginForm();
    if (fLogin.ShowDialog() == DialogResult.OK)
    {
        Application.Run(new MainForm());
    }
    else
    {
        Application.Exit();
    }
}</code>

In Program.cs, create and display a modal login form (fLogin) as a dialog box. If the user provides valid credentials, ShowDialog() will return DialogResult.OK, triggering the creation of a new MainForm instance via Application.Run(). Otherwise, the application will exit (Application.Exit()).

The above is the detailed content of How to Show the Main Form After Successful Login in a Windows Forms Application Without Closing the App?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn