ucef ucef - 7 days ago 5
C# Question

Handle pressing up arrow on keyboard when focus is on button

I have to catch when the user is pressing the up arrow on the keyboard, while the button has the focus. I have written this code to handle the KeyUp event for the button:

private void btnValider_KeyUp(object sender, KeyEventArgs e)
{
if (e.KeyCode == Keys.Up)
{
//do stuff
}
}


but this function didn't handle pressing the up arrow key.

I don't know if it what i want to do is possible or if i have to handle this event from the form ?

Answer

As Hans Passant suggested,

protected override bool ProcessCmdKey(ref Message msg, Keys keyData)
    {
        if (keyData == Keys.Up && btnValider.Focused)
        {
            MessageBox.Show("hit");

            return true;
        }
        else
            return base.ProcessCmdKey(ref msg, keyData);
    }
Comments