2011-02-08 82 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; 
     } 
    }