Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles
(untagged)

Multiple Subsequent Main Forms in C# Apps

0.00/5 (No votes)
22 Nov 2011 1  
A useful technique that could be used for winform apps which require a login dialog

In this Quick Answer question[^], aspdotnetdev recommended to the original poster to run Application.Run twice. I had never thought of doing that before, but I actually found a reason to do so in my own development process (aspdotnet gave me divine dispensation to post a tip/trick about it, but I needed a real-world example before I could do it - here's that example).

We have an application that requires the user to login. My solution was based on this little info gem.

First, I created a login form. In the form, I placed the requisite userID/password textboxes, and a Login and Cancel buttons. The handlers for these buttons set the DialogResult property of the form (Login sets it to DialogResult.OK and Cancel sets it to DialogResult.Cancel).

Then, in program.cs, I have the following code:

static class Program
{
    private static FormSplash m_formSplash = null; 

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

        m_formSplash = new FormSplash();
        Application.Run(m_formSplash);
        if (m_formSplash.DialogResult == DialogResult.OK)
        {
            Application.Run(new FormMain());
        }
    }
}

What happens is that the splash form runs, and when it exits, the application class itself determines whether or not to exit the app or run the next form.

This sure beats running the main form and having special processing in that form to handle the login form. It's A LOT cleaner (code abstraction/separation is almost always a good thing), and easier to maintain, especially if there are copious comments in the Form classes to notify the maintenance programmer (or remind the original programmer) what's happening, and why.

License

This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here