[英]C# How can i move a picturebox with mouse
我嘗試用c#編寫一個程序,在其中嘗試裝飾聖誕樹,我想用鼠標摘地球並戴在聖誕樹上。 我可以執行此操作,但是在為第二個Picturebox編寫代碼並運行該程序后,地球僅以一個速度運動,僅對一個PictureBox即可。 這是我的代碼。 如何解決呢?
PS picturebox1和2是地球,而pb_brad是聖誕樹。
public partial class Form1 : Form
{
Point location = Point.Empty;
public Form1()
{
InitializeComponent();
pictureBox1.Parent = pb_brad;
pictureBox1.BackColor = Color.Transparent;
pictureBox2.Parent = pb_brad;
pictureBox2.BackColor = Color.Transparent;
}
private void pictureBox1_MouseDown(object sender, MouseEventArgs e)
{
if (e.Button == MouseButtons.Left)
{
location = new Point(e.X, e.Y);
}
}
private void pictureBox1_MouseMove(object sender, MouseEventArgs e)
{
if (location != Point.Empty)
{
Point newlocation = this.pictureBox1.Location;
newlocation.X += e.X - location.X;
newlocation.Y += e.Y - location.Y;
this.pictureBox1.Location = newlocation;
}
}
private void pictureBox1_MouseUp(object sender, MouseEventArgs e)
{
location = Point.Empty;
}
private void pictureBox2_MouseDown(object sender, MouseEventArgs e)
{
if (e.Button == MouseButtons.Left)
{
location = new Point(e.X, e.Y);
}
}
private void pictureBox2_MouseMove(object sender, MouseEventArgs e)
{
if (location != Point.Empty)
{
Point newlocation = this.pictureBox1.Location;
newlocation.X += e.X - location.X;
newlocation.Y += e.Y - location.Y;
this.pictureBox2.Location = newlocation;
}
}
private void pictureBox2_MouseUp(object sender, MouseEventArgs e)
{
location = Point.Empty;
}
}
我看到您正在pictureBox2的MouseMove事件處理程序中使用pictureBox1。
順便說一句,我看到兩個PictureBox的處理程序都相同。 為什么不對所有PictureBox使用相同的處理程序,並通過sender參數獲取當前的PictureBox?
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.