don
don

Reputation: 203

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);

Upvotes: 4

Views: 7546

Answers (3)

BenCamps
BenCamps

Reputation: 1834

The Button control in WinForms will eat Enter, Space, Tab, ESC, and a few other special key's press events. One method to intercept these events is to override Control.ProcessDialogKey. Or you can override IsDialogKey to say if a key should be handled as a special case.

A another option is to set KeyPreview = true on you parent Form. Then you can handle all KeyPress events at the Form level and use Form.ActiveControl if you need to see what control has Focus

Upvotes: 0

Igor Quirino
Igor Quirino

Reputation: 1195

Enter and space can be handled using click event.

this.myButton.Click += new EventHandler(myButton_Click);

Upvotes: 2

Reza Aghaei
Reza Aghaei

Reputation: 125197

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");
    }
}

Upvotes: 4

Related Questions