Windows Forms: How to make a PictureBox move in C#

This post shows you How to make a PictureBox move with mouse inside a Form using C# .NET Windows Forms Application.

We will create a custom PictureBox control allows you to move image in picturebox with mouse using c# code.

Creating a new Windows Forms Application project, then create a new class named CustomPictureBox and and make it inherit from PictureBox control.

How to create custom control in c#

public class CustomPictureBox : PictureBox
{
    public CustomPictureBox(IContainer container)
    {
        container.Add(this);
    }

    Point point;

    protected override void OnMouseDown(MouseEventArgs e)
    {
        base.OnMouseDown(e);
        point = e.Location;
    }

    protected override void OnMouseMove(MouseEventArgs e)
    {
        base.OnMouseMove(e);
        if (e.Button == MouseButtons.Left)
        {
            this.Left += e.X - point.X;
            this.Top += e.Y - point.Y;
        }
    }
}

C# Moving picturebox with mouse

You need to override the OnMouseDown and OnMouseMove event handlers that allows you to move a PictureBox with mouse inside a form.

You can do the same with another control that lets you move a control by dragging it with the mouse in C#

How to add custom control in toolbox in c#

After you finish creating a custom control, you need to rebuild your project. Next open your form designer, on the side of the Visual Studio Toolbox window you will see the custom control that you have created automatically added to the Visual Studio Toolbox.

how to add custom control in toolbox in c#

C# Move image in picturebox with mouse

Dragging the CustomPictureBox control from the Visual Studio Toolbox to your winform, then add an image to the CustomPictureBox control.

c# picturebox

Select the Size Mode is StretchImage.

c# move image in picturebox with mouse

Press F5 to run your application, then you can move image in PictureBox with mouse in c#.

VIDEO TUTORIAL