Search code examples
c#winformsdrawing

How to draw a line in windows forms c#?


I have a C# windows forms application. I need to draw a straight line (from one point to another), and I have the option to delete it while keeping all the other lines (drawn earlier). And the line is removed when I click on it. I see different ways to clear everything, not just one line that was drawn earlier.


Solution

  • You could use Graphics.DrawLine to create the line (System.Drawing namespace)

    DrawLine(Pen, xCord1, yCord1, xCord2, yCord2) where Pen gives the color and width for line Pen (System.Drawing.Brush brush, float width);

    Now, there is no built in way to detect click on line - it's just pixels on the screen. So you would have to do some custom code and store the lines (if you are creating multiple lines) in array/list. To detect the click on line drawn with this method, you will need to detect if the point clicked falls on the line with some calculations e.g. How do I detect click on a line in Windows Forms

    Then remove the line from the array if the clicked point falls on it - you will end up with non-clicked lines in the array. Finally, perform Graphics.Clear or this.Invalidate() and redraw the lines left in array.