0

I'm a somewhat beginner to C# using Visual Studio 2019 and currently creating a game and am struggling to find a way to create a generic mousedown/mousemove event handler to move pictureboxes created at runtime through a class constructor with the mouse

I've figured out how to move them how I want but right now it only works when I click the form and not the picturebox itself, which is far from ideal. Is there a way to create a generic event handler that is able to determine which pictureBox is clicked and moves only that one? And how would I go about doing that? If it helps I've added the pictureBoxes to Form1's Controls in order to display them. The code is the class constructor of how the pictureBox is created at runtime using the line:

"new Piece(new Position(100, 100), 200, 300, form);"

        public Piece(Position pos, int xSize, int ySize, Form form)
    {
        this.pos = pos;
        this.xSize = xSize;
        this.ySize = ySize;
        pic = new PictureBox();
        pic.BackColor = Color.LightBlue;
        pic.Size = new System.Drawing.Size(xSize, ySize);
        UpdateImgPos();
        pic.Visible = true;
        form.Controls.Add(pic);
        Pieces.Add(this);
        childPlatforms = new List<Platform>();
    }
Lotus
  • 3
  • 2

1 Answers1

0

If i understand it right, then you can use the event of the picturebox. The Parameter sender is the Control, which fire the event.

PictureBox pictureBox = new PictureBox();
// add image, set start location, etc...
pictureBox.Size = new System.Drawing.Size(100, 50);
pictureBox.MouseDown += PictureBox_MouseDown;
this.Controls.Add(pictureBox);

// ...

private void PictureBox_MouseDown(object sender, MouseEventArgs e)
{
      // cast object sender to PictureBox pictureBox
      if (!(sender is PictureBox pictureBox)) return;

      pictureBox.Location = CursorPosition;
}
  • This seems like it would work! But I'm still a bit stuck on how to get the "pictureBox.MouseDown += PictureBox_MouseDown;" line to work as the pictureboxes are created in a class constructor outside of the Form class, I've added the code for how they're created if that helps and thanks for the help in advance. – Lotus Jul 14 '21 at 02:14