如何在C#中启动另一个主要表单

clo*_*oud 5 c# forms

首先,我显示一个登录表单。当用户输入正确的ID和密码时,我想显示另一个表单,然后关闭登录表单。以下是我启动登录表单的方式。

static class Program
{
    /// <summary>
    /// The main entry point for the application.
    /// </summary>
    [STAThread]
    static void Main()
    {
        Application.EnableVisualStyles();
        Application.SetCompatibleTextRenderingDefault(false);
        Application.Run(new FrmLogin());
    }
}
Run Code Online (Sandbox Code Playgroud)

现在,当我想显示主窗体时,我调用该类的dispose()方法FrmLogin,但是应用程序立即结束。我的解决方案是将class 的visible属性更改FrmLoginfalse,我知道这是不对的,请提出解决方案。

Dam*_*ith 1

您可以将登录表单显示为对话框,如果登录成功,则可以将主表单运行为:

static class Program
{
     public static bool isValid = false;
    /// <summary>
    /// The main entry point for the application.
    /// </summary>
    [STAThread]
    static void Main()
    {
        Application.EnableVisualStyles();
        Application.SetCompatibleTextRenderingDefault(false);
        using (FrmLogin login = new FrmLogin())
        { 
            login.ShowDialog(); 
            if (isValid)
            {           
                Application.Run(new MainForm());
            }
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

在您的 FrmLogin 中,验证用户并设置DialogResultOk。在这里我是在按钮单击事件上完成的。

private void btnLogin_Click(object sender, EventArgs e)
{

    Program.isValid= true; // impliment this as method 
    if(Program.isValid)
    {
      this.DialogResult = DialogResult.OK;
      // or this.Close();
    }
    else
    {
      //else part code
    }
}
Run Code Online (Sandbox Code Playgroud)