0
votes

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>();
    }
1
Can you share code about how you are creating runtime pictures? - Shervin Ivari
Please share code, and what engine you used for designing. - CSakura
@ShervinIvari I've added the code you asked for! - Lotus
@CSakura I've added the code! And I'm using Visual Studio 2019 using windows forms - Lotus

1 Answers

0
votes

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;
}