2011-02-08 83 views
0

我要移动一个按钮鼠标,一切正常,但是当我在按钮的窗口,左边和顶部的按钮的鼠标移动(左上角)将光标定位POS机。移动控件通过鼠标

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

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 
     p.X = e.X + button1.Left; 
     p.Y = e.Y + button1.Top; 
     button1.Left = p.X; 
     button1.Top = p.Y ; 

    } 

} 

private void button1_MouseUp(object sender, MouseEventArgs e) 
{ 
    clicked = false; 
} 
+0

ClientToScreen和ScreenToClient坐标 – 2011-02-08 16:02:07

回答

3

我发现它...

这里是全码:

private void button1_MouseDown(object sender, MouseEventArgs e) 
{ 
    if (e.Button == System.Windows.Forms.MouseButtons.Left) 
    { 
     Point p = ConvertFromChildToForm(e.X, e.Y, button1); 
     iOldX = p.X; 
     iOldY = p.Y; 
     iClickX = e.X; 
     iClickY = e.Y; 
     clicked = true; 
    } 

} 

private void button1_MouseMove(object sender, MouseEventArgs e) 
{ 
    if (clicked) 
    { 
     Point p = new Point();//in form coordinates 
     p.X = e.X + button1.Left; 
     p.Y = e.Y + button1.Top; 
     button1.Left = p.X - iClickX; 
     button1.Top = p.Y - iClickY; 

    } 

} 

private void button1_MouseUp(object sender, MouseEventArgs e) 
{ 
    clicked = false; 
} 
+0

完整的代码应该显示`ConvertFromChildToForm`方法。 – 2012-05-19 05:04:52

1

我不知道我是否正确,但以防万一知道了...如果

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

否,也许在该按钮的鼠标位置为(30,12);
所以我们不能说其按钮的中心。 – 2011-02-09 02:54:45

8

此:问题是将光标定位在按钮(或另一组件)的中心,就可以通过考虑宽度和高度achive它是你需要的全部

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