What's the recommended way to open a new form and close the current/first form?

后端 未结 3 1869
不思量自难忘°
不思量自难忘° 2021-01-29 11:02

I\'m building an application that have a initial form for login and if the user is authorized this form (login) should close and the application main form should open.

I

相关标签:
3条回答
  • 2021-01-29 11:20

    This is how you do it:

    FormSecond f = new FormSecond();
    f.Show();
    this.Close();
    
    0 讨论(0)
  • 2021-01-29 11:25

    If you start with the login form and close it, you no longer have any thread to run on. So (one of) the solution would be to run a different initial form and make that form launch the login form. Once the login form is no longer useful, you can close that and return control to the initial form. You can then spawn any kind of form as needed from the initial form.

    0 讨论(0)
  • 2021-01-29 11:41

    if the user is authorized this form (login) should close and the application main form should open.

    Recommendations number 1, 2 and 3 strongly state to not do this. Adding your own authentication layer to the one that Windows already provides is never not a mistake. You will never get it as secure and well tested as the Windows login. And there's a serious security risk, users will re-use their login password. If you need any extra info for a login beyond Environment.UserName and the groups the user belongs to then you can get that from the domain controller with the System.DirectoryServices namespace.

    But you'll throw that caution to the wind. The boilerplate solution is to modify the Main() method in Program.cs and use ShowDialog() to display a login form. Which should return DialogResult.OK when the login is good, DialogResult.Cancel if it is not. You use it like this:

        [STAThread]
        static void Main() {
            Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault(false);
            using (var login = new LoginForm()) {
                if (login.ShowDialog() != DialogResult.OK) return;
            }
            Application.Run(new Form1());
        }
    
    0 讨论(0)
提交回复
热议问题