Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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);
like image 311
don Avatar asked Oct 14 '25 09:10

don


2 Answers

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");
    }
}
like image 56
Reza Aghaei Avatar answered Oct 16 '25 23:10

Reza Aghaei


Enter and space can be handled using click event.

this.myButton.Click += new EventHandler(myButton_Click);
like image 43
Igor Quirino Avatar answered Oct 17 '25 00:10

Igor Quirino



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!