I have a Windows Forms application in C# with drawing panel and a button - for drawing a line.
When you click the button, you can draw a line for 2 random points.
Pen p = new Pen(Color.Black, 5);
//point for start
Point ps = new Point();
//point for end
Point pe = new Point();
private void drawPanel_MouseDown(object sender, MouseEventArgs e)
{
ps.X = e.X;
ps.Y = e.Y;
pe = ps;
}
private void drawPanel_MouseMove(object sender, MouseEventArgs e)
{
// when button is clicked for drawing draw = true;
if (draw)
{
if (e.Button == MouseButtons.Left)
{
pe = new Point(e.X, e.Y);
}
}
}
private void drawPanel_MouseUp(object sender, MouseEventArgs e)
{
onMouseUpFlag = true;
}
private void drawPanel_Paint(object sender, PaintEventArgs e)
{
Graphics g = drawPanel.CreateGraphics();
if (onMouseUpFlag)
{
g.DrawLine(p, ps, pe);
g.Dispose();
}
}
The program has some flaws :
- When you draw a line it shows it, only if the main window is moved somewhere(usually when I hide it)
- It can draw only 1 line.
Any suggestions how to fix these bugs ?
EDIT
I've read you answers and made some changes :
Pen p = new Pen(Color.Black, 5);
Point ps = new Point();
Point pe = new Point();
List<Point> linesStart= new List<Point>();
List<Point> linesEnd= new List<Point>();
private void drawPanel_MouseDown(object sender, MouseEventArgs e)
{
ps.X = e.X;
ps.Y = e.Y;
linesStart.Add(ps);
pe = ps;
}
private void drawPanel_MouseMove(object sender, MouseEventArgs e)
{
if (e.Button == MouseButtons.Left)
{
pe = new Point(e.X, e.Y);
//adding end point .. actually adds a lot of points
linesEnd.Add(pe);
}
}
bool onMouseUpFlag = false;
private void drawPanel_MouseUp(object sender, MouseEventArgs e)
{
onMouseUpFlag = true;
drawPanel.Invalidate();
}
private void drawPanel_Paint(object sender, PaintEventArgs e)
{
if (onMouseUpFlag)
{
for (int i = 0; i < linesStart.Count; i++)
{
e.Graphics.DrawLine(p, linesStart[i], linesEnd[i]);
}
}
}
Now I'm trying to fix the DrawLine for multiple lines. Paint event can do multiple line but only the starting point is fine. Somehow the end point is not very correct. Where I can set exactly the last point of the MouseMove event ?