1

我有一个登录屏幕,我想在密码文本框中按 enter 时激活它。问题是即使它有效,当我关闭表单时,应用程序的行为就像输入仍然被按下并且表单以无限循环打开。

这是我的代码:

  private void textBox2_TextChanged(object sender, EventArgs e)
        {
            textBox2.KeyDown += new KeyEventHandler(textBox2_KeyDown);

        }

 public void textBox2_KeyDown(object sender, KeyEventArgs e)
        {
            if (user == Username[1] && pass == passwords[1])
                {
                    MessageBox.Show("Login successfull", "Welcome, HR");
                    UpdateDBForm newEmployee = new UpdateDBForm();
                    this.Hide();
                    newEmployee.ShowDialog();  
                    return;

                }
}

我该如何解决这个问题?谢谢。

4

2 回答 2

1

正如@bash.d 所写,您要多次分配事件,请执行一次(由设计人员或在构造函数中(在InitializeComponent调用后)或在Form_Load事件中)

private void Form_Load(object sender, EventArgs e)
{
   textBox2.KeyDown += new KeyEventHandler(textBox2_KeyDown);
}

你也写过你想在用户点击进入后登录,所以你必须添加这个if

public void textBox2_KeyDown(object sender, KeyEventArgs e)
{
    if (e.KeyCode == Keys.Enter)
    {
        if (user == Username[1] && pass == passwords[1])
        {
            MessageBox.Show("Login successfull", "Welcome, HR");
            UpdateDBForm newEmployee = new UpdateDBForm();
            this.Hide();
            newEmployee.ShowDialog();
            return;        
        }
    }
}
于 2013-08-07T11:22:38.160 回答
1

You are assigning the KeyDown-EventHandler everytime your text changes:

private void textBox2_TextChanged(object sender, EventArgs e)
{
   textBox2.KeyDown += new KeyEventHandler(textBox2_KeyDown); // EVIL!
}

This means, that the more often you input data into your textbox, the more the eventhandler will be assigned and when you eventually hit enter it will be called as many times. Assign the eventhandler once, i.e. in your constructor and this should work.

于 2013-08-07T11:17:53.933 回答