Search code examples
c#winformskeydownkeyup

Handle KeyDown and KeyUp events triggering with arrow buttons on keyboard in WinForms desktop application


I'm trying to figure out, how to handle KeyDown and KeyUp events triggering with arrow buttons on keyboard in WinForms C# desktop application, instead using the button1:

 private void button1_Click(object sender, EventArgs e)
 {
     y = y - 10; // Go up
     moveGraphicObject();
 }

but if I use arrow keys, events does not fires with or without other controls on form:

 private void Form1_KeyDown(object sender, KeyEventArgs e)
 {
    if (e.KeyCode == Keys.Left)
    {
       x = x - 10;
    }

    if (e.KeyCode == Keys.Right)
    {
       x = x + 10;
    }

    if (e.KeyCode == Keys.Up)
    {
       y = y - 10;
    }

    if (e.KeyCode == Keys.Down)
    {
       y = y + 10;   
    }   
    
    moveGraphicObject();
 }

Solution

  • Check out PreviewKeyDown event. MSDN has a pretty good example here

    By default, KeyDown does not fire for the ARROW keys PreviewKeyDown is where you preview the key. Do not put any logic here, instead use the KeyDown event after setting IsInputKey to true.