Rey232
Rey232

Reputation: 3

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

Upvotes: 0

Views: 737

Answers (1)

Alex Seleznyov
Alex Seleznyov

Reputation: 945

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.

Upvotes: 1

Related Questions