c# - 登录表单不会关闭

标签 c# authentication

我正在开发一个供个人使用的项目(简单的电话簿)。

基本上,我有三种形式:Main(主要的)、Settings(用于配置设置的)和Login (登录表单,仅当用户选中启动时要求输入密码的选项时才应启动)。澄清一下:启动 .EXE 文件时,它应该加载 Main 表单,除非选中请求通过的选项(Properties.Settings.Default.AskForPass == true) - 当它应该首先运行登录表单时。

这是登录表单的样子:

Login

我不知道如何让事情以正确的方式工作。

我试图将 Program.cs 中的行从 Main 更改为 Login:

namespace Phonebook
{
    static class Program
    {
        /// <summary>
        /// The main entry point for the application.
        /// </summary>
        [STAThread]
        static void Main()
        {
            Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault(false);
            Application.Run(new Login());
        }
    }
}

然后如果用户输入正确的用户名和密码并单击“确定”按钮:

private void button1_Click(object sender, EventArgs e)
    {
        if (txtUsername.Text == Properties.Settings.Default.MyUsername && txtPassword.Text == Properties.Settings.Default.MyPassword)
        {
            Main f1 = new Main();
            Login f3 = new Login();
            f1.Show();
            f3.Close();
        }
        else
        {
            DialogResult dialogResult = MessageBox.Show("Wrong password! Do you want to try again?", "Warning", MessageBoxButtons.RetryCancel, MessageBoxIcon.Warning);
            if (dialogResult == DialogResult.Retry)
            {
                return;
            }
            else if (dialogResult == DialogResult.Cancel)
            {
                this.Close();
            }
        }
    }

登录表单保留在后台,如您所见:

Contacts

我希望关闭登录 表单,这样它就不会出现在后台。问题是现在 Login 表单是主要表单,如果我尝试关闭它,整个应用程序都会关闭。

我曾尝试更改所有者,但没有成功。

有什么想法吗?请帮忙!

最佳答案

您正在创建一个新的登录表单并关闭它。尝试

this.Hide();
f1.ShowDialog();
this.Close();

另一种方法是在登录表单上返回一个状态,然后检查它和 Application.Run() 主表单:

在登录表单中:

private bool LoggedIn;
public bool IsLoggedIn { get { return LoggedIn; } }

然后在按钮中点击:

LoggedIn = true; 
this.Close();

在 Program.cs 中:

Login f = new Login();
Application.Run(f);

if (f.IsLoggedIn)
    Application.Run(new Main());

关于c# - 登录表单不会关闭,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20221529/

相关文章:

c# - Windows 手机 8 : Back Button

C# 重新加载系统环境变量

authentication - 使用 WinSCP.com(命令行)无需密码登录到服务器

java - Vaadin 21 查看角色

php - Laravel session 立即过期 (Laravel 5.5)

c# - 如何编写允许数据从 native 流向托管的自定义编码(marshal)拆收器?

c# - 使用 LINQ 将一个列表中的值分配给另一个列表

c# - 为什么 .NET 的 Scala 编译器会忽略 val 的含义?

asp.net-mvc - 使用 IIS Express 8.0 在 Visual Studio 2013 中进行调试时,无法使用 Windows 身份验证访问[授权] MVC 方法

asp.net - 处理 WIF 中的并发身份提供商声明