Detect Enter Key C#

╄→гoц情女王★ 提交于 2019-12-01 15:38:41

问题


I have the following code which does not show the MessageBox when enter/return is pressed.

For any other key(i.e. letters/numbers) the MessageBox shows False.

private void cbServer_TextChanged(object sender, EventArgs e)
{
    if (enterPressed)
    {
        MessageBox.Show("Enter pressed");
    }
    else
        MessageBox.Show("False");
}

private void cbServer_Keydown(object sender, KeyEventArgs e)
{
    if (e.KeyCode == Keys.Enter || e.KeyCode == Keys.Return)
    {
        enterPressed = true;
        MessageBox.Show("Enter presssed: " + enterPressed);

    }
    else
        enterPressed = false;
}

Any ideas?

EDIT: Above code, I thought the issue was with the _Keydown even so I only posted that.


回答1:


This is because when you press Enter TextChanged event won't fire.




回答2:


in your form designer class (formname.designer.cs) add this :

this.KeyPress += new System.Windows.Forms.KeyPressEventHandler(this.Login_KeyPress);

and add this code to backbone code (formname.cs):

void Login_KeyPress(object sender, KeyPressEventArgs e)
    {
        if (e.KeyChar == (char)13)
            MessageBox.Show("ENTER has been pressed!");
        else if (e.KeyChar == (char)27)
            this.Close();
    }



回答3:


private void textBox_PreviewKeyDown(object sender, KeyEventArgs e)
 {
            if (e.Key == Key.Enter)
            {
                MessageBox.Show("Enter key pressed");
            }
            else if (e.Key == Key.Space)
            {
                MessageBox.Show("Space key pressed");
            }
}

Use PreviewKeyDown event to detect any key before shown in textbox or input



来源:https://stackoverflow.com/questions/11984238/detect-enter-key-c-sharp

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!