C# 通过鼠标在窗体中抓取、移动和放下控件
您好,我发现这段代码可能会帮助我解决以下问题,我正在尝试通过鼠标在我的表单中进行拖放和移动标签C# 通过鼠标在窗体中抓取、移动和放下控件,c#,.net,winforms,C#,.net,Winforms,您好,我发现这段代码可能会帮助我解决以下问题,我正在尝试通过鼠标在我的表单中进行拖放和移动标签 private Point MouseDownLocation; private void MyControl_MouseDown(object sender, MouseEventArgs e) { if (e.Button == System.Windows.Forms.MouseButtons.Left) { Mouse
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;
}
}
但是当我将mousemove和mousedown作为事件来标记时,我试图抓住标签并用鼠标移动,它会随着整个表单移动
请问代码应该在哪里改进
谢谢您的时间。您需要移动控件,而不是使用此。左(即表单):
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;
}
}
此外,您可能希望在按下按钮时捕获鼠标,然后在按下按钮时释放鼠标。这将防止非常快的运动“破坏”你的逻辑。有关详细信息,请参阅