Control that simulates dragging of the window title bar

c#, controls, drag, winforms

Solution

In addition to my other answer, you can do this manually in a Control like this:

Point dragOffset;

protected override void OnMouseDown(MouseEventArgs e) {
    base.OnMouseDown(e);
    if (e.Button == MouseButtons.Left) {
        dragOffset = this.PointToScreen(e.Location);
        var formLocation = FindForm().Location;
        dragOffset.X -= formLocation.X;
        dragOffset.Y -= formLocation.Y;
    }
}

protected override void OnMouseMove(MouseEventArgs e) {
    base.OnMouseMove(e);

    if (e.Button == MouseButtons.Left) {
        Point newLocation = this.PointToScreen(e.Location);

        newLocation.X -= dragOffset.X;
        newLocation.Y -= dragOffset.Y;

        FindForm().Location = newLocation;
    }
}

EDIT: Tested and fixed - this now actually works.

Problem

I've built a custom control, and I'd like to allow people to click and drag on my control just as if they were dragging on the window title bar. What is the best way to do this? So far I've been unsuccessful at leveraging the mouse down, up, and move events to decipher when the window needs to be moved.

Original source