我对C#很新,但如果我的语法不准确,那么试着学习如何忍受我。我能够创建一个带按钮的图片框,它出现在屏幕上。然后我可以通过鼠标按下/鼠标移动功能在屏幕上移动它。然后我点击按钮来实例化另一个要创建的图片框,并且也可以移动那个图片框,但是当我尝试移动第一个图片框时,第二个图片框移动而变得疯狂。有没有办法在实例化时引用或标记框,这样当我点击它们中的任何一个时我可以在屏幕上移动它们?
public partial class Form1 : Form
{
Point MP;
private static Control PB;
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
int picSizeX = Properties.Resources.police.Width / 3;
int picSizeY = Properties.Resources.police.Height / 3;
PictureBox pb = new PictureBox();
pb.Location = new Point(100, 100);
pb.Size = new Size(picSizeX, picSizeY);
pb.Image = new Bitmap(Properties.Resources.police);
pb.SizeMode = PictureBoxSizeMode.StretchImage;
Controls.Add(pb);
pb.Tag = "veh";
PB = pb;
pb.MouseDown += Pb_MouseDown;
pb.MouseMove += Pb_MouseMove;
pb.MouseHover += Pb_MouseHover;
}
private void Pb_MouseHover(object sender, EventArgs e)
{
PB.MouseHover += PB_MouseHover;
}
private void PB_MouseHover(object sender, EventArgs e)
{
}
private void Pb_MouseDown(object sender, MouseEventArgs e)
{
MP = e.Location;
}
private void Pb_MouseMove(object sender, MouseEventArgs e)
{
if (e.Button == MouseButtons.Left)
{
PB.Left = e.X + PB.Left - MP.X;
PB.Top = e.Y + PB.Top - MP.Y;
}
}
}
答案 0 :(得分:3)
实际上没有必要在班级拥有控制权。
在事件方法中有一个名为 object sender
的参数,其中包含对引发事件的控件/对象的引用。
Point MP;
//private Control PB; //commented out as it is not required
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
int picSizeX = Properties.Resources.police.Width / 3;
int picSizeY = Properties.Resources.police.Height / 3;
PictureBox pb = new PictureBox();
pb.Location = new Point(100, 100);
pb.Size = new Size(picSizeX, picSizeY);
pb.Image = new Bitmap(Properties.Resources.police);
pb.SizeMode = PictureBoxSizeMode.StretchImage;
Controls.Add(pb);
pb.Tag = "veh";
//PB = pb;
pb.MouseDown += Pb_MouseDown;
pb.MouseMove += Pb_MouseMove;
pb.MouseHover += Pb_MouseHover;
}
private void Pb_MouseHover(object sender, EventArgs e)
{
Control pbObj = sender as PictureBox; //sender refers to control that raised the event
pbObj.MouseHover += PB_MouseHover;
}
private void PB_MouseHover(object sender, EventArgs e)
{
}
private void Pb_MouseDown(object sender, MouseEventArgs e)
{
MP = e.Location;
}
private void Pb_MouseMove(object sender, MouseEventArgs e)
{
Control pbObj = sender as PictureBox; //sender refers to control that raised the event
if (e.Button == MouseButtons.Left)
{
pbObj.Left = e.X + pbObj.Left - MP.X;
pbObj.Top = e.Y + pbObj.Top - MP.Y;
}
}