Drag change the control position

Point mouseDownPoint = Point.Empty;
Rectangle rect = Rectangle.Empty;
bool isDrag = false;

private void pictureBox1_MouseDown(object sender, MouseEventArgs e)
{
    if (e.Button == MouseButtons.Left)
    {
        mouseDownPoint = e.Location;
        rect = pictureBox1.Bounds;
    }
}

private void pictureBox1_MouseUp(object sender, MouseEventArgs e)
{
    if (e.Button == MouseButtons.Left)
    {
        if (isDrag)
        {
            isDrag = false;
            pictureBox1.Location = rect.Location;
            this.Refresh();
        }
        reset();
    }
}

private void pictureBox1_MouseMove(object sender, MouseEventArgs e)
{
    if (e.Button == MouseButtons.Left)
    {
        isDrag = true;
        rect.Location = getPointToForm(new Point(e.Location.X - mouseDownPoint.X, e.Location.Y - mouseDownPoint.Y));
        this.Refresh();
    }
}

private void reset()
{
    mouseDownPoint = Point.Empty;
    rect = Rectangle.Empty;
    isDrag = false;
}
private Point getPointToForm(Point p)
{
    return this.PointToClient(pictureBox1.PointToScreen(p));
}

Guess you like

Origin www.cnblogs.com/jizhiqiliao/p/10930612.html