Search code examples
c#winformskeyboardenter

C# Visual Studio, how to detect Enter key press when a button has focus


I have the following code that detects the enter key press and works ok. however, if you click a button on the form then it stops working i.e. the button pressed now has focus and enter press goes straight to that button.

private void Form1_Load(object sender, EventArgs e)
{
    KeyPreview = true;
}

private void Form1_KeyUp(object sender, KeyEventArgs e)
{
    if (e.KeyCode == Keys.Enter)
    {
        MessageBox.Show("Enter pressed");
    }
}

I have tried the following with no success;

  1. Using forms PreviewKeyEvent instead of keyUp
  2. Using forms KeyDown instead of KeyUp
  3. Creating a button that is selected as the form's 'AcceptButton'

My workaround is to create a button that the form 'selects' on load, which will be clicked on entering. Then to have a timer running to maintain focus on that button in case any others are selected. This seems a bit of a shoddy solution.

Any ideas would be appreciated. Seems like I am missing something obvious.

Phil


Solution

  • Override ProcessCmdKey:

    protected override bool ProcessCmdKey( ref Message msg, Keys keyData ) {
        if( keyData == Keys.Enter ) {
            // Enter is pressed
    
            return true; //return true if you want to suppress the key.
        }
    
        return base.ProcessCmdKey( ref msg, keyData );
    }