How to make a PictureBox move in C#

By FoxLearn 7/18/2024 8:12:10 AM   12.98K
To make a PictureBox move with the mouse inside a Form in a C# Windows Forms Application, you'll need to handle the mouse events and update the PictureBox position accordingly.

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

Calculate the new position for the PictureBox based on the mouse coordinates (e.X and e.Y), then adjust the position so that the mouse cursor is at the center of the PictureBox by subtracting its width and height from the coordinates.

Update the Location property of the PictureBox with the new calculated coordinates.

C# Moving picturebox with mouse

You need to handle the MouseMove event of the Form to track the mouse movement and update the position of the PictureBox. You can 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