I’m trying to draw out pictureboxes during runtime as I can do right from the toolbox. That is, set the location at the mouselocation, resize it as I hold down the button and drag it across the form. All that I’ve accomplished in the code. But as I start the draw the second picturebox the first one disappears, I want to keep adding more pictureboxes to the form, if I remove the MouseMove event and move PictureBox pb1 = new PictureBox(); down to the MouseDown event it lets me add more buttons, but then I can’t resize them obviously.
int cellSize = 10;
int numOfCells = 500;
PictureBox pb1 = new PictureBox();
int Mx, My;
public Form1()
{
InitializeComponent();
this.DoubleBuffered = true;
}
public void pictureBox1_MouseMove(object sender, MouseEventArgs e)
{
Point p = new Point(e.X, e.Y);
Mx = p.X;
My = p.Y;
int xSnap = (Mx / cellSize) * cellSize;
int ySnap = (My / cellSize) * cellSize;
pb1.BackColor = (Color.Red);
if (e.Button == MouseButtons.Left)
{
pb1.Size = new Size(xSnap - pb1.Left, ySnap - pb1.Top);
}
}
private void pictureBox1_MouseDown(object sender, MouseEventArgs e)
{
Point p = new Point(e.X, e.Y);
Mx = p.X;
My = p.Y;
int xSnap = (Mx / cellSize) * cellSize;
int ySnap = (My / cellSize) * cellSize;
pb1.Location = new Point(xSnap, ySnap);
pictureBox1.Controls.Add(pb1);
}
You’re always re-using the same
PictureBoxinstance.You need to create a new instance every time you want to add a new one, by writing
new PictureBox().