c# - 有没有一种简单的方法来合并登录屏幕?

标签 c# winforms authentication

我知道我可以通过在表单显示(Load() 事件,IIRC)之前的事件中显示登录表单来劫持表单,但是(可能是愚蠢地)试图“偷工减料”并创建快速且肮脏的登录屏幕,我陷入了困境。

这是我对现有项目所做的(事后添加的登录表单):

1) Created the login form
2) Changed program.cs so that this login form is now the first form created
3) Added code to the login form that shows the "main" form if the login is successful. I then Hide the login form.

这导致应用程序永远不会关闭(除了通过 Shift+F5),因为隐藏的主窗体仍然潜伏着。因此,我在“主”表单的 FormClosing 事件中添加了一个“Close()”,认为这会导致整个应用程序关闭(IOW,隐藏的登录表单)。

但是(也许恰如其分),这并没有解决我的问题,而是导致 “System.Windows.Forms.dll 中发生类型为‘System.StackOverflowException’的未处理异常”

现在我不知道我是否应该继续这种快速而肮脏的尝试(以及如何)或减少我的损失并恢复到在加载事件中显示登录表单的方法 [ology]。

更新

Alex M 的解决方案奏效了。您需要做的唯一额外的事情就是在您的登录表单中做这样的事情:

private void buttonLogin_Click(object sender, EventArgs e)
{
    String userName = textBoxUserName.Text.Trim();
    String pwd = textBoxPassword.Text.Trim();
    if ((userName == "donMcLean") || (pwd == "Drove my Chevy to the levee but the levee was dry, them good ole boys were drinking whiskey & Rye"))
    {
        this.DialogResult = DialogResult.OK;
    }
    else
    {
        MessageBox.Show("Incorrect User Name and/or Password");
    }
}

最佳答案

创建顺序不是特别重要。您可以使用 form.ShowDialog() 显示登录表单。这样做会处理表单并解决您所描述的问题。

例如:

var login = new LoginForm();
var mainForm = new MainForm();

if (login.ShowDialog() != DialogResult.Ok) 
{
      return; // Exit the application
}

Application.Run(mainForm);

关于c# - 有没有一种简单的方法来合并登录屏幕?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11268452/

相关文章:

c# - 编译器如何从 LAMBDA 表达式推断委托(delegate)类型?

c# - ASP MVC 5 在 URL 中隐藏区域(路由)

c# - 使用对象列表填充 datagridview

c# - Visual C# 2008,读取 XML 文件并填充 listView

c# - 访问 Azure 中的大文件

c# - 我可以编写一个通用方法来调用其他超时方法吗?

c# - 获取屏幕边缘和网页之间的距离

asp.net - 使用父网站登录子站点 : best practice?

git - HTTPS 的 Maven JGitFlow 插件身份验证

mysql - 如何使用hibernate检查表中是否存在数据