通过鼠标抓取、移动和放下表单中的控件

本文关键字:表单 放下 控件 移动 鼠标 抓取 | 更新日期: 2023-09-27 18:33:24

您好,我找到了这段代码,可以帮助我解决以下问题,我正在尝试通过鼠标在我的表单中拖放和移动标签。

 private Point MouseDownLocation;
    private void MyControl_MouseDown(object sender, MouseEventArgs e)
    {
        if (e.Button == System.Windows.Forms.MouseButtons.Left)
        {
            MouseDownLocation = e.Location;
        }
    }
    private void MyControl_MouseMove(object sender, MouseEventArgs e)
    {
        if (e.Button == System.Windows.Forms.MouseButtons.Left)
        {
            this.Left = e.X + this.Left - MouseDownLocation.X;
            this.Top = e.Y + this.Top - MouseDownLocation.Y;
        }
    }

但是当我将鼠标移动和鼠标按下作为要标记的事件时,我尝试抓住标签并用鼠标移动,它会随着整个表单一起移动。

请问代码应该在哪里改进?

谢谢你的时间。

通过鼠标抓取、移动和放下表单中的控件

而不是使用 this.Left(这是表单),您需要移动控件:

private void MyControl_MouseMove(object sender, MouseEventArgs e)
{
    if (e.Button == System.Windows.Forms.MouseButtons.Left)
    {
        MyControl.Left = e.X + MyControl.Left - MouseDownLocation.X;
        MyControl.Top = e.Y + MyControl.Top - MouseDownLocation.Y;
    }
}

此外,您可能希望将鼠标捕获在按钮向下,并在按钮向上时释放它。 这将防止非常快的运动"破坏"你的逻辑。 有关详细信息,请参见 Windows 窗体中的鼠标捕获。