所以,我有一个带有背景图像(图片框)的表格和一些随机位置上的动态名称为pic [i]的图片框。
我在for循环中创建了这段代码。
pic[i].MouseDown += new MouseEventHandler(picMouseDown);
pic[i].MouseMove += new MouseEventHandler(picMouseMove);
pic[i].MouseUp += new MouseEventHandler(picMouseUp);
下面我展示了相应的事件。
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;
}
所以,我知道在" picMouseMove"," i"具有for循环结束时的值。
我想要做的是在" picMouseMove"上获取pic [i] id。事件,以便用户可以成功地拖动拼图。
答案 0 :(得分:1)
您需要强制 sender
到PictureBox
。然后你可以像访问它一样访问它。
只需更改
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 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();
}
}