Windows Forms: How to Move PictureBox with Arrow Keys in C#

This post shows you How to Move PictureBox using Arrow Keys in C# .NET Windows Forms Application.

Creating a new Windows Forms Application project, then create a new class with name CustomPictureBox and make it inherit the PictureBox control that allow moving a Picture Box using arrow keys in C# Windows Forms Application.

C# Move PictureBox with arrow keys

The PictureBox control is not Selectable by default. Therefore it can't handle Keyboard events. To solve the problem, you should make the control selectable by using the SetStyle method.

public class CustomPictureBox : PictureBox
{
    public CustomPictureBox(IContainer container)
    {
        SetStyle(ControlStyles.Selectable, true);
        SetStyle(ControlStyles.UserMouse, true);
        TabStop = true;
        container.Add(this);
    }

    protected override void OnEnter(EventArgs e)
    {
        base.OnEnter(e);
        this.Invalidate();
    }

    protected override void OnLeave(EventArgs e)
    {
        base.OnLeave(e);
        this.Invalidate();
    }

    protected override void OnPaint(PaintEventArgs pe)
    {
        if (this.Focused)
            ControlPaint.DrawFocusRectangle(pe.Graphics, ClientRectangle);
        base.OnPaint(pe);
    }

    protected override void OnPreviewKeyDown(PreviewKeyDownEventArgs e)
    {
        int x = this.Location.X;
        int y = this.Location.Y;

        if (e.KeyCode == Keys.Right)
        {
            e.IsInputKey = true;
            x += 1;
        }
        else if (e.KeyCode == Keys.Left)
            x -= 1;
        else if (e.KeyCode == Keys.Up)
            y -= 1;
        else if (e.KeyCode == Keys.Down)
            y += 1;
        this.Location = new Point(x, y);
        base.OnPreviewKeyDown(e);
    }
}

You can easily create a custom PictureBox by inheriting the PictureBox control that allows you to make a picturebox move by itself in c#.

You can also, do the same way as above to move object with arrow keys in c#.

Rebuild your project, you will see the CustomPictureBox automatically added to the Visual Studio Toolbox.

add custom control to visual studio toolbox

C# Moving object on Form

Dragging the CustomPictureBox control to your form designer.

How to Move PictureBox with Arrow Keys in C#

Clicking the Choose Image... link to add a new image to the CustomPictureBox, then set the Size Mode to StretchImage.

choose image picturebox

Finally, Press F5 to run your project and play the demo.