C#按Enter键按下按钮

时间:2017-05-13 16:59:08

标签: c#

我已经编写了以下代码,除了按Enter键仍然没有点击“登录”按钮外,一切正常。帮助!

int failedAttempts;

private void uiPasswordTextBox_KeyDown(object sender, KeyEventArgs e)
{
    if (e.KeyCode == Keys.Enter)
    {
        uiLoginButton.PerformClick();
    }
}

private void uiLoginButton_Click(object sender, EventArgs e)
{
    if (uiPasswordTextBox.Text == "alacaZam")
    {
        uiPasswordTextBox.Text = string.Empty;
        this.uiLogOffButton.Enabled = true;
        this.uiMarkEntryNameTextBox.Enabled = true;
        this.uiMarkEntryClassTestTextBox.Enabled = true;
        this.uiMarkEntryConicalTextBox.Enabled = true;
        this.uiMarkEntryDestructiveTextBox.Enabled = true;
        this.uiStoreMarksButton.Enabled = true;
        this.uiShowMarksAZButton.Enabled = true;
        this.uiShowMarks100_0Button.Enabled = true;
    }
    else if (failedAttempts <= 1)
    {
        failedAttempts++;
        MessageBox.Show("You are permitted 3 attempts. " + (3 - failedAttempts) + " attempt/s remaining.", "Incorrect Password", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
    }
    else if (failedAttempts == 2)
    {
        MessageBox.Show("Access Denied", "Incorrect Password. Entered 3 Times", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
        Application.Exit();
    }
}

2 个答案:

答案 0 :(得分:1)

你必须使用&#39; AcceptButton&#39;表格的财产。将所需按钮分配给&#39; AcceptButton&#39;表格的属性如下所示

public Form1()
{
   InitializeComponent();
   AcceptButton = this.uiLoginButton;
}

无需写下KeyDown&#39;事件。您可以删除&#39; uiPasswordTextBox_KeyDown&#39;事件

答案 1 :(得分:0)

除了手动调用click方法之外,只需创建第三个方法来保存uiLoginButton_Click()方法中的所有逻辑,然后将uiLoginButton_Click()调用为调用所述方法的单行代码。

然后只需将uiLoginButton.PerformClick()方法转换为该方法。

手动触发订阅的事件方法设计很差。