本文介绍了如何关闭一个登录表单,并显示主窗体没有我申请截止?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在我的项目(​​登录和主)两种形式。

I have two forms in my project (Login and Main).

我试图以accoomplish是,如果登录成功,我必须显示在主窗体并关闭登录表单。

What I'm trying to accoomplish is, if the login is successful, I must show the Main form and close the Login form.

我有这样的方法,登录表单关闭登录表单时,登录成功。但主要形式的不显示。

I have this method in Login form that closes the Login form when the login is successful. But the Main form doesn't show.

public void ShowMain()
{
    if(auth()) // a method that returns true when the user exists.
    {             
        var main = new Main();
        main.Show();
        this.Close();
    }
    else
    {
        MessageBox.Show("Invalid login details.");
    }         
}

我试图隐藏登录表单,如果登录过程是成功的。但它困扰我,因为我知道,而我的程序正在运行的登录表单仍然有太多,应当将其关闭吗?

I tried hiding the Login form if the login process is successful. But it bothers me because I know while my program is running the login form is still there too, it should be closed right?

应该是什么的正确方法呢?谢谢...

What should be the right approach for this?Thanks...

推荐答案

你的主要形式是不显示的原因是因为一旦你关闭登录表单,您的应用程序的消息泵关闭,这将导致整个应用程序退出。该的Windows消息循环是联系在一起的登录表单,因为那是你已经设置在项目属性启动形式之一。看看你的的Program.cs文件,你会看到code中的责任位: Application.Run(新LoginForm的())。检查出的文档,该方法在这里 MSDN ,该更详细地解释了这一点。

The reason your main form isn't showing is because once you close the login form, your application's message pump is shut down, which causes the entire application to exit. The Windows message loop is tied to the login form because that's the one you have set as the startup form in your project properties. Look in your "Program.cs" file, and you'll see the responsible bit of code: Application.Run(new LoginForm()). Check out the documentation for that method here on MSDN, which explains this in greater detail.

最好的解决办法是将code出你的登录表单进入的Program.cs文件。当你的程序第一次启动时,您将创建并显示登录窗体作为模式对话框(它运行在您的code,直到它关闭剩下的一个独立的消息循环,并阻止执行)。当登录对话框关闭,你会检查它的的DialogResult 属性,查看是否登录成功。如果是,则可以使用启动的主要形式 Application.Run (从而创造了主消息循环);否则,您可以退出应用程序,而不显示任何形式的。事情是这样的:

The best solution is to move the code out of your login form into the "Program.cs" file. When your program first starts, you'll create and show the login form as a modal dialog (which runs on a separate message loop and blocks execution of the rest of your code until it closes). When the login dialog closes, you'll check its DialogResult property to see if the login was successful. If it was, you can start the main form using Application.Run (thus creating the main message loop); otherwise, you can exit the application without showing any form at all. Something like this:

static void Main()
{
    LoginForm fLogin = new LoginForm();
    if (fLogin.ShowDialog() == DialogResult.OK)
    {
        Application.Run(new MainForm());
    }
    else
    {
        Application.Exit();
    }
}

这篇关于如何关闭一个登录表单,并显示主窗体没有我申请截止?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

11-01 16:23