我正在开发一个供个人使用的项目(简单的电话簿)。
基本上,我有三种形式:Main(主要的)、Settings(用于配置设置的)和Login (登录表单,仅当用户选中启动时要求输入密码的选项时才应启动)。澄清一下:启动 .EXE 文件时,它应该加载 Main 表单,除非选中请求通过的选项(Properties.Settings.Default.AskForPass == true) - 当它应该首先运行登录表单时。
这是登录表单的样子:
我不知道如何让事情以正确的方式工作。
我试图将 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();
}
}
}
登录表单保留在后台,如您所见:
我希望关闭登录 表单,这样它就不会出现在后台。问题是现在 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/