I have some trouble with drawing on picturebox in visual studio c#. I want do draw a line between 2 points that i get either with mouse clicks or with inserting coordinates manualy. So i have created 2 events, picterbox paint event where i made a pen and graphics, and mouse click event where i want to store mouse clicks so i can connect two points. I dont know how to properly store those two clicks. I was doing something wit e.Location but it doesnt register the second click and always stores my first click so i dont draw nothing because of that. So can someone pls tell me what is the best way to store the clicks so i can later use them in g.drawline(p,point1,pont2)...
You will need a flag (boolean member will work) that indicates the first click has been saved, then check this flag in the OnClick event. If the flag is set, save the point to a different location. Clear the flag after the second click has been processed (this is assuming you only want to save 2 points)
This is because the Paint method of pictureBox is only called if it has to redraw the PictureBox. Try doing your two clicks, minimize the form then restore it. Add this to the 'else' part of your MouseClick event:
Ok never mind above post. I figure it out. Now i have another problem. With this code i can draw as many lines as i want... But i would like, that after 2 drawn lines, those lines dissapear and i can draw another 2 lines and so on... And i have one more question about bitmap. I used this:
pictureBox1.Image = new Bitmap(pictureBox1.Width, pictureBox1.Height);
What is the diference between bitmap and normal picture box.
Ty for your help! ;)
Here is the code :
List<Point> p1List = new List<Point>();
List<Point> p2List = new List<Point>();
private void pictureBox1_Paint(object sender, PaintEventArgs e)
Graphics g = e.Graphics;
Pen p = new Pen(Color.Black, 1);
for (int x = 0; x < p1List.Count; x++)
g.DrawLine(p, p1List[x], p2List[x]);
private void pictureBox1_MouseClick(object sender, MouseEventArgs e)
if (p1.X == 0)
p1.X = e.X;
p1.Y = e.Y;
p2.X = e.X;
p2.Y = e.Y;
p1.X = 0;
If you want to limit the number of points just make sure your List object doesn't have too many in it. Put a check right after you add your two new points to see how large the Count property is, if it is over 4 then remove the first one (index 0) twice.
if (p2List.Count == 2)
The problem here is when i have count ==2 it doest draw 2 lines but it clear all lines right after i draw the second line. But if i have count > 2 then i need to draw the third line to make all go away.
if (p2List.Count > 2)
if (p1List.Count > 2)
But if i use this code i line always stays drawn. And i want program to work like this. I draw 2 lines on picturebox, and when i star to draw the third line, both lines that were drawn beofre dissapears and the screen is empty..