Search code examples
c#.netwinformskeypress

Button KeyPress Not Working for Enter Key


I have a button for which I set the KeyPress event.

this.myButton.KeyPress += new KeyPressEventHandler(this.myButtonEvent_keypress);

private void myButtonEvent_keypress(object sender, KeyPressEventArgs e)
{
     if (e.KeyChar == (char)Keys.Return || e.KeyChar == (char)Keys.Space)
     {
          // do something
     }
}

Now whenever the Space key is pressed, I get the event triggered. This part works fine.

But for some reason, the Enter key press is not triggering the KeyPress event. Also Alt, Ctrl, Shift are not working.

How can I make the button receive Enter key press?

UPDATE:

I tried below too without any luck

this.myButton.MouseClick += new MouseEventHandler(myButton_Click);

Solution

  • When a Button has focus and you press Enter or Space the Click event raises.

    So to handle Enter or Space it's enough to handle Click event and put the logic you need there.

    So you just need to use button1.Click += button1_Click;

    private void button1_Click(object sender, EventArgs e)
    {
        MessageBox.Show("Clicked!");
    } 
    

    If you really want to know if Enter or Space was pressed, you can hanlde PreviewKeyDown event:

    private void button1_PreviewKeyDown(object sender, PreviewKeyDownEventArgs e)
    {
        if(e.KeyCode== Keys.Enter)
        {
            MessageBox.Show("Enter");
        }
        if (e.KeyCode == Keys.Space)
        {
            MessageBox.Show("Space");
        }
    }