通过鼠标移动控件

我要用鼠标移动按钮,一切正常,但是当我在按钮窗口上移动鼠标时,按钮的左上方(左上角)将位于光标位置。

我不希望这种情况发生。 我的代码中的错误在哪里?

private void button1_MouseDown(object sender, MouseEventArgs e) { if (e.Button == System.Windows.Forms.MouseButtons.Left) { clicked = true; } } private void button1_MouseMove(object sender, MouseEventArgs e) { if (clicked) { Point p = new Point();//in form coordinates pX = eX + button1.Left; pY = eY + button1.Top; button1.Left = pX; button1.Top = pY ; } } private void button1_MouseUp(object sender, MouseEventArgs e) { clicked = false; } 

这就是你所需要的

  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 = eX + this.Left - MouseDownLocation.X; this.Top = eY + this.Top - MouseDownLocation.Y; } } 

我找到了……

这是完整的代码:

 private void button1_MouseDown(object sender, MouseEventArgs e) { if (e.Button == System.Windows.Forms.MouseButtons.Left) { Point p = ConvertFromChildToForm(eX, eY, button1); iOldX = pX; iOldY = pY; iClickX = eX; iClickY = eY; clicked = true; } } private void button1_MouseMove(object sender, MouseEventArgs e) { if (clicked) { Point p = new Point();//in form coordinates pX = eX + button1.Left; pY = eY + button1.Top; button1.Left = pX - iClickX; button1.Top = pY - iClickY; } } private void button1_MouseUp(object sender, MouseEventArgs e) { clicked = false; } 

我不知道我是否正确,但以防万一…如果问题是将光标定位在按钮(或其他组件)的中心,您可以通过考虑宽度和高度来实现:

  private void button1_MouseMove(object sender, MouseEventArgs e) { if (clicked) { Point p = new Point(); //in form coordinates pX = eX + button1.Left - (button1.Width/2); pY = eY + button1.Top - (button1.Height/2); button1.Left = pX; button1.Top = pY; } }