是否有一种简单的方法来合并登录屏幕?

时间:2012-06-29 20:19:50

标签: c# winforms login

我知道我可以通过在显示(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),因为隐藏的主要表单仍然潜伏着。所以,我在“main”表单的FormClosing事件中添加了一个“Close()”,认为这会导致整个应用程序关闭(IOW,隐藏登录表单)。

但是(也许是合适的),而不是解决我的问题,这会导致“System.Windows.Forms.dll中发生类型'System.StackOverflowException'的未处理异常”

现在我不知道我是否应该继续这种快速和肮脏的尝试(以及如何)或减少我的损失并恢复到show-the-login-form-in-the-Load事件方法[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");
    }
}

1 个答案:

答案 0 :(得分:5)

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

例如:

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

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

Application.Run(mainForm);