Dragging an UserControl

Hello,

I have a bit of a situation. I have a UserControl which I will want to drag around a panel, I've found many tutorials on dragging things into controls, but I actually wish to change the X,Y location of the control.

I've tried using this:


...
   customControl.MouseDown += new MouseEventHandler(DragIt);
}

public
void DragIt(object sender, MouseEventArgs e) {
   customControl.Location = new Point(e.X, e.Y);
}


 


But it would only drag when its clicked, and wouldn't simulate a real drag across the screen.

If anyone could help, I'd appreciate it. :)


Answer this question

Dragging an UserControl

  • Wolvorine

    Hello,

    Looking at what you wrote, I seems it would move your control's top left corner to where ever on the control you clicked the mouse Is that correct

    The way I have managed it in the past is along the lines of:
    Save the controls original position and the point where the mouse was clicked down.

    protected override void OnMouseDown(MouseEventArgs e)

    {

    oldPoint = Form.MousePosition;

    moving = true // Is we move while mouse button is held down then Yes we are moving.

    oldX = this.Location.X; // Controls locations

    oldY = this.Location.Y; //    ""

    }

    // Then for every mouse move event move your control by the same amount:

    protected override void OnMouseMove(MouseEventArgs e)

    {

    if (moving)

    {

    int xDiff, yDiff;

    newPoint = Form.MousePosition;

    xDiff = newPoint.X - oldPoint.X;  // How much have we moved

    yDiff = newPoint.Y - oldPoint.Y;

    oldPoint.X = newPoint.X; // Update the oldpoint to the new point.

    oldPoint.Y = newPoint.Y;

    oldX = oldX + xDiff; // Now define the new location for the control

    oldY = oldY + yDiff;

    this.Location = new Point( oldX, oldY);

    }
    }

    // NOTE: IMPORTANT
    // Then finally on the "mouseup" event set "moving" back to false

    Probably not the most attractive or efficient way of doing it but it worked for me.
    Hope it helps


  • Dragging an UserControl