通过鼠标在Form中抓取,移动和放下控件

时间:2013-09-30 17:20:54

标签: c# .net winforms

你好我发现这段代码可以帮助我解决以下问题,我试图通过鼠标在我的表单中拖放,移动标签。

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

但是,当我将鼠标移动并将mousedown作为事件标记并且我试图抓住标签并随着鼠标移动时,它会移动整个表格。

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

感谢您的时间。

1 个答案:

答案 0 :(得分:2)

您需要移动控件,而不是使用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;
    }
}

此外,您可能希望在按钮上捕获鼠标,然后在按钮上将其释放。这将阻止非常快速的动作“打破”你的逻辑。有关详细信息,请参阅Mouse Capture in Windows Forms