In my program I have a
List
of
picturebox
and during the program when I push a button a new
picturebox
will be created. But I want to draw 2 lines between two selected pictureboxes by
MouseDown
and
MouseUp
but no line will be drawn.
Here is my code:
public partial class Form1 : Form
{
int x1, y1, x2, y2, x3, y3, x4, y4;
List<PictureBox> pics = new List<PictureBox>();
PictureBox thisPB;
int i = 0;
int j;
void drawlines(int x1, int y1, int x2, int y2)
{
Graphics g = this.CreateGraphics();
Pen p = new Pen(Color.Black,2);
g.DrawLine(p, x1, y1, x1, y2);
g.DrawLine(p, x1, y2, x2, y2);
g.Dispose();
}
private void button1_Click(object sender, EventArgs e)
{
pics.Add(new PictureBox());
pics[i].Name = "pic" + i.ToString();
pics[i].Left = 200 * i;
pics[i].Top = 100 * i;
pics[i].Height = 100;
pics[i].Width = 100;
pics[i].SizeMode = PictureBoxSizeMode.StretchImage;
pics[i].Image = (Image)Properties.Resources.Tulips;
pics[i].MouseDown += new MouseEventHandler(pic_MouseDown);
pics[i].MouseUp+=new MouseEventHandler(pic_MouseUp);
this.Controls.Add(pics[i]);
i++;
}
void pic_MouseMove(object sender, MouseEventArgs e)
{
if (e.Button == MouseButtons.Left)
{
PictureBox thisPB = (PictureBox)sender;
thisPB.Left = e.X;
thisPB.Top = e.Y;
}
}
void pic_MouseDown(object sender, MouseEventArgs e)
{
x3 = e.X;
y3 = e.Y;
thisPB = (PictureBox)sender;
x1 = (thisPB.Right - thisPB.Left) / 2;
y1 = (thisPB.Top - thisPB.Bottom) / 2;
}
void pic_MouseUp(object sender, MouseEventArgs e)
{
x4 = e.X;
y4 = e.Y;
thisPB = (PictureBox)sender;
x2 = (thisPB.Right - thisPB.Left) / 2;
y2 = (thisPB.Top - thisPB.Bottom) / 2;
drawlines(x1, y1, x4, y4);
}
}
How can I choose a picture to be selected for drawing line?