How do I tell when the enter key is pressed in a TextBox?

天涯浪子 提交于 2019-12-05 09:55:01

问题


Basically, I want to be able to trigger an event when the ENTER key is pressed. I tried this already:

private void input_KeyDown(object sender, KeyEventArgs e)
    {
        if (e.Equals("{ENTER}"))
        {
            MessageBox.Show("Pressed enter.");
        }
    }

But the MessageBox never shows up. How can I do this?


回答1:


Give this a shot...

private void input_KeyDown(object sender, KeyEventArgs e) 
{                        
    if(e.KeyData == Keys.Enter)   
    {  
        MessageBox.Show("Pressed enter.");  
    }             
}



回答2:


To add to @Willy David Jr answer: you also can use actual Key codes.

private void input_KeyDown(object sender, KeyEventArgs e)
{
    if (e.KeyChar == 13)
    {
        MessageBox.Show("Pressed enter.");
    }
}



回答3:


You can actually just say

private void input_KeyDown(object sender, KeyEventArgs e)
{
    if (e.Key == Key.Enter)
    {
        MessageBox.Show("Pressed enter.");
    }
}



回答4:


If your Form has AcceptButton defined, you won't be able to use KeyDown to capture the Enter.

What you should do is to catch it at the Form level. Add this code to the Form:

protected override bool ProcessCmdKey(ref Message msg, Keys keyData)
{
    if ((this.ActiveControl == myTextBox) && (keyData == Keys.Return))
    {
        //do something
        return true;
    }
    else
    {
        return base.ProcessCmdKey(ref msg, keyData);
    }
}



回答5:


You can use the Keypress event. If you are just looking for the "Enter" keypress, then you probably don't care about modifier keys (such as Shift and/or Ctrl), which is why most would use KeyDown instead of Keypress. A second benefit is to answer the question that is almost always asked after implementing any of the other answers: "When I use the referenced code, why does pressing "Enter" cause a beep?" It is because the Keypress event needs to be handled. By using Keypress, you solve both in one place:

private void input_KeyPress(object sender, KeyPressEventArgs e)
{
    if (e.KeyChar == (char)Keys.Enter)
    {
        // Your logic here....
        e.Handled = true; //Handle the Keypress event (suppress the Beep)
    }
}



回答6:


You can also do this:

  private void input_KeyDown(object sender, KeyEventArgs e) 
  {                        
    if(e.KeyCode== Keys.Enter)   
    {  
        //Your business logic here.
    }             
  }

The only difference with KeyCode vs KeyData is that KeyCode can detect modifiers combination with KeyCode (e.g. CTRL, Shift + A) which you don't need here.



来源:https://stackoverflow.com/questions/11806166/how-do-i-tell-when-the-enter-key-is-pressed-in-a-textbox

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