拖拽更改控件位置

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

建议使用dll减少闪烁,

[DllImport("user32.dll", EntryPoint = "ReleaseCapture")]
public static extern void ReleaseCapture();
[DllImport("user32.dll", EntryPoint = "SendMessage")]
public static extern void SendMessage(int hwnd, int wMsg, int wParam, int lParam);

private void panel1_MouseDown(object sender, MouseEventArgs e)
{
    if (e.Button == MouseButtons.Left)
    {
        ReleaseCapture();
        SendMessage((int)panel1.Handle, 0xA1, 2, 0);
    }
}

处理WM_NCHITTEST消息,

public partial class CustomGroupBox : System.Windows.Forms.GroupBox
{
    public const int WM_NCHITTEST = 0x0084;

    public const int HTCAPTION = 2;
    public const int HTLEFT = 10;
    public const int HTRIGHT = 11;
    public const int HTTOP = 12;
    public const int HTTOPLEFT = 13;
    public const int HTTOPRIGHT = 14;
    public const int HTBOTTOM = 15;
    public const int HTBOTTOMLEFT = 16;
    public const int HTBOTTOMRIGHT = 17;
    protected override void WndProc(ref Message m)
    {
        if (m.Msg == WM_NCHITTEST)
        {
            m.Result = new IntPtr(HTCAPTION);
            return;
        }
        else
            base.WndProc(ref m);
    }
}
原文地址:https://www.cnblogs.com/jizhiqiliao/p/10930612.html