我正在尝试在运行时绘制图片框,就像我可以直接从工具箱中所做的那样。也就是说,在鼠标位置设置位置,在我按住按钮并将其拖过表单时调整它的大小。我在代码中完成的所有工作。但是当我开始绘制第二个图片框时,第一个图片框消失了,我想继续向表单添加更多图片框,如果我删除MouseMove
事件并向下移动PictureBox pb1 = new PictureBox();
到MouseDown
事件,它可以让我添加更多按钮,但是我无法调整大小他们显然。
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);
}