开发者

How to close a windows form and transfer control to an other form?

I have encountered a problem in my application. I have two forms, one that is loaded when my application is started that asks for a password and other is shown when the user logs in with correct password.

How can I close the login form and have the user proceed to next form that is actual application?

Currently I hide the login form, but the requirement is to c开发者_如何转开发lose the login form to prevent extra processing. However, when I close the login form my application exits and when I hide the login form but close the actual application form the login form remains open and prevents my application from closing because the login form is still running in background.

How can in fix this?


The way I would typically handle this is have code similar to what follows in the main method;

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

    if (PerformLogin())
    {           
        Application.Run(new MainForm());
    }
}

private static bool PerformLogin()
{
    using (LoginForm loginForm = new LoginForm())
    {
        if (loginForm.ShowDialog() == DialogResult.OK)
        {
            return AuthenticateUser(loginForm.UserName, loginForm.Password);
        }
        else
        {
            return false;
        }
    }
}

Since the login form is created and destroyed within the PerformLogin method, it does not remain in memory longer than necessary.


I would say simplest approach would just be to display the first form in the Load event of the second as a modal dialog. If the password auth fails you can call Close in the event handler and the second form will go away as well.

And obviously you would use the second form as the one passed to Application.Run in your Main() function.


Even simpler - get into the main method. open the first form as DIALOG, initialize application, open second form with Application.Run. Finished.


I presume, you have used

 LoginForm.Hide();

Use

 LoginForm.Close();

I may be wrong too... but just trying my luck...

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜