2011-11-29 126 views
-2

我需要移動(繪製)與矩形相同的鼠標位置的矩形。有一個代碼,鼠標位於矩形的中間。將矩形移動到與矩形相同的鼠標位置?

private void pictureBox1_MouseMove_1(object sender, MouseEventArgs e) 
{ 
    if (e.Button == MouseButtons.Left) 
    { 
     rect.X = e.X - (rect.Width/2); 
     rect.Y = e.Y - (rect.Height/2); 

     rect.Width = rect.Width; 
     rect.Height = rect.Height; 
     pictureBox1.Invalidate(); 
    } 
} 
+2

問題應該有一個問號 – Snowbear

回答

0

您需要將鼠標位置存儲在MouseDown處理程序中,並考慮偏移量而不是將其居中。

假設你的座標(相對於RECT)保存的MouseDown:

private void pictureBox1_MouseMove_1(object sender, MouseEventArgs e) 
{ 
    if (e.Button == MouseButtons.Left) 
    { 
     rect.X = e.X - downPos.X; 
     rect.Y = e.Y - downPos.Y; 

     rect.Width = rect.Width; 
     rect.Height = rect.Height; 
     pictureBox1.Invalidate(); 
    } 
} 
+0

我存儲X,Y鼠標,但我不'噸知道如何使用它們。 – gormit

+0

查看已更新的答案 – Deanna

+0

是的,我忘記了存儲相關的cooridanates,謝謝! – gormit