Click here to Skip to main content
15,615,787 members
Please Sign up or sign in to vote.
2.67/5 (3 votes)
See more:
How can I Draw a line on a Form using c#?

When I click on point I want to draw a line to another point and move the line around.

(like paint in windows)

thanks for any help.
Updated 7-Jan-11 3:38am

You will have to handle the MouseDown, MouseMove and MouseUp events.
1. In MouseDown, you will get the start point of line.
2. In MouseMove, draw the line to have rubberband effect.
3. In MouseUp you will get the end point of line.
4. In the Paint event, redraw the line from start point to endpoint.

One of the replies already has code to draw the line.

I would suggest to draw the line on a Panel or other suitable container rather than directly on the form.
Share this answer
As an addition to Yusuf's answer, You would have to incorporate the use of the Mousedown and Mouseup handlers on the form. I won't lead you by the hand because I think you would benefit from figuring this out from the hints.
You need to get a starting point and keep it around. When the user releases the button you will need to permanently draw the line on the form. The process of actually drawing the line is well described in Yusuf's answer so I won't repeat that part here.
Share this answer
Yusuf 7-Jan-11 11:28am    
Good point Marc. I left that part as an exercise for the OP.
Look at this MSDN sample code.

System.Drawing.Pen myPen;
myPen = new System.Drawing.Pen(System.Drawing.Color.Red);
System.Drawing.Graphics formGraphics = this.CreateGraphics();
formGraphics.DrawLine(myPen, 0, 0, 200, 200);

Source: See link above
Share this answer
Mostafa Elsadany 7-Jan-11 10:25am    
i find that on Microsoft site but is not working with me
You can adapt this code to suit your needs:
using System.Drawing;
using System.Windows.Forms;
public partial class Form1 : Form
    private bool isMouseDown = false;
    private Point startPoint;
    private Point endPoint;
    public Form1()
        MouseDown += new MouseEventHandler(Form1_MouseDown);
        MouseUp += new MouseEventHandler(Form1_MouseUp);
        MouseMove += new MouseEventHandler(Form1_MouseMove);
    private void Form1_MouseDown(object sender, MouseEventArgs e)
        if (e.Button == MouseButtons.Left)
            startPoint = e.Location;
            isMouseDown = true;
    private void Form1_MouseUp(object sender, MouseEventArgs e)
        if (e.Button == MouseButtons.Left)
            isMouseDown = false;
    private void Form1_MouseMove(object sender, MouseEventArgs e)
        if (isMouseDown)
            endPoint = e.Location;
    protected override void OnPaint(PaintEventArgs e)
        using (Pen pen = new Pen(ForeColor))
            e.Graphics.DrawLine(pen, startPoint, endPoint);
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