Kountay Dwivedi
Kountay Dwivedi

Reputation: 27

How to detect ENTER key on button

I am using this code. panelButtons[] is an array of buttons.

        for (i = 0; i <= 15; i++)
        {
            int temp = i;
            panelButtons[temp].KeyPress += new KeyPressEventHandler(checkKeyPress);
        }
    }
    private void checkKeyPress(object a, KeyPressEventArgs b)
    {
        if(b.KeyChar==(char)Keys.Enter || b.KeyChar==(char)Keys.Return)
        {
            DialogResult result = MessageBox.Show("Enter");
        }
    }

The problem is that, it is NOT detecting enter key. I have searched a lot on net, but all I get is how to detect ENTER key on textbox. This method, and many other similar to this(like KeyDown idea) are not working.

Upvotes: 0

Views: 492

Answers (1)

swe
swe

Reputation: 1455

Handle the PreviewKeyDown-Event of that Button and set the PreviewKeyDownEventArgs.IsInputKey to True

Private Sub Button1_PreviewKeyDown(sender As Object, e As PreviewKeyDownEventArgs) Handles Button1.PreviewKeyDown
    If e.KeyCode = Keys.Enter Then e.IsInputKey = True
End Sub

Upvotes: 2

Related Questions