Click here to Skip to main content
15,886,519 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
When user press the left button and move the mouse it should appears a straight line(not permanent line) from previous point to the current mouse moving position. Finally a real straight line will appear when the user releases the left mouse. please help me ..how do i do it?
private void pictureBox1_MouseDown(object sender, MouseEventArgs e)
{
    if (e.Button == MouseButtons.Left)
    {
        points.Add(e.Location);
        pictureBox1.Invalidate();
    }
}

private void pictureBox1_Paint(object sender, PaintEventArgs e)
{
    if (points.Count > 1)
       e.Graphics.DrawLines(Pens.Black, points.ToArray());
}
Posted
Updated 1-May-14 22:27pm
v3

1 solution

It's not a big change from what you have,
In the MouseDown, clear the points collection, and add the start point. Invalidate the PictureBox. Add a class level bool which says "Collecting points" and set it to true in the MouseDown event handler.
Then handle the MouseMove event, and if you are collecting points add each new point in there - invalidate again.
In the MouseUp handler, set "Collecting Points" to false.

This won't make them permanent - you are drawing on the screen, not the image in the PictureBox - but if you need to do that, then use the Graphics.FromImage method to get a context, and use the DrawLines method on that instead (don't forget to Dispose the Context when you have finished with it) - but you probably want to do that just once when the user is happy with the lines.

Do note that the location you get from the mouse events will be in terms of the form, so if the picture box doesn't fill it, then the lines will be offset quite a bit and you may need to move them.
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900