问题
So, I have a form with a background image (picturebox) and some jigsaw puzzle pieces (pictureboxes created dynamically named pic[i]) on random locations.
I have this piece of code inside the for-loop creating the pieces.
pic[i].MouseDown += new MouseEventHandler(picMouseDown);
pic[i].MouseMove += new MouseEventHandler(picMouseMove);
pic[i].MouseUp += new MouseEventHandler(picMouseUp);
And below I show the corresponding events.
int x = 0;
int y = 0;
bool drag = false;
private void picMouseDown(object sender, MouseEventArgs e)
{
// Get original position of cursor on mousedown
x = e.X;
y = e.Y;
drag = true;
}
private void picMouseMove(object sender, MouseEventArgs e)
{
if (drag)
{
// Get new position of picture
pic[i].Top += e.Y - y; //this i here is wrong
pic[i].Left += e.X - x;
pic[i].BringToFront();
}
}
private void picMouseUp(object sender, MouseEventArgs e)
{
drag = false;
}
So, I am aware that inside the "picMouseMove", "i" has the value it had when the for loop ended.
What I want to do is to get the pic[i] id on the "picMouseMove" event so the user can actually drag the puzzle piece successfully.
回答1:
You need to cast the sender
to a PictureBox
. Then you can access it as if you knew it by name.
Simply change
private void picMouseMove(object sender, MouseEventArgs e)
{
if (drag)
{
// Get new position of picture
pic[i].Top += e.Y - y; //this i here is wrong
pic[i].Left += e.X - x;
pic[i].BringToFront();
}
}
to
private void picMouseMove(object sender, MouseEventArgs e)
{
if (drag)
{
PictureBox pb = (PictureBox ) sender;
// Get new position of picture
pb.Top += e.Y - y;
pb.Left += e.X - x;
pb.BringToFront();
}
}
来源:https://stackoverflow.com/questions/24475152/how-can-i-drag-dynamically-created-pictureboxes