How to Move PictureBox with Arrow Keys in C#

By FoxLearn 7/16/2024 9:26:47 AM   9.52K
To move a PictureBox control using arrow keys in C#, you can handle the KeyDown event of the form or the control that hosts the PictureBox.

Here’s a step-by-step guide on how move PictureBox with arrow keys in C#.

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)
    {
        // Determine which key is pressed and move PictureBox accordingly
        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;

        // Update the PictureBox location
        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.

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.