How to achieve control free dragging in WinForms?

To achieve free dragging of the controls, you can follow these steps:

Set the event handlers for the MouseDown, MouseMove, and MouseUp events of the control.

private Point mouseOffset;
private bool isMouseDown = false;

private void Control_MouseDown(object sender, MouseEventArgs e)
{
    if (e.Button == MouseButtons.Left)
    {
        isMouseDown = true;
        Control control = (Control)sender;
        mouseOffset = new Point(e.Location.X, e.Location.Y);
    }
}

private void Control_MouseMove(object sender, MouseEventArgs e)
{
    if (isMouseDown)
    {
        Control control = (Control)sender;
        Point mousePos = control.PointToScreen(new Point(e.X, e.Y));
        control.Location = new Point(mousePos.X - mouseOffset.X, mousePos.Y - mouseOffset.Y);
    }
}

private void Control_MouseUp(object sender, MouseEventArgs e)
{
    isMouseDown = false;
}

Bind the above event handler to the control that needs to be dragged.

control.MouseDown += Control_MouseDown;
control.MouseMove += Control_MouseMove;
control.MouseUp += Control_MouseUp;

By following the above steps, you can achieve the free dragging of the control. When the user presses the left mouse button and drags on the control, the control will adjust its position according to the distance the mouse moves.

bannerAds