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.
-
Technically, if you don't find a better solution, you can use a rectangle with a height of 1. From there it's simply a bit of math calculating the position and rotation to make it work. – palatinus-sb Apr 07 '21 at 08:37
-
https://learn.microsoft.com/tr-tr/dotnet/api/system.drawing.graphics.drawline?view=net-5.0 does this explain what it is wanted? – Emre İriş Apr 07 '21 at 08:37
-
If you're expecting to be able to click it to remove it, I'd probably go with a button element that you can position, stretch into a line, and give it an event to be removable on click. – Luc Apr 07 '21 at 08:38
-
[Example](https://stackoverflow.com/questions/32919918/how-to-draw-line-and-select-it-in-panel/32920894?r=SearchResults&s=3|17.7000#32920894) - You will need to decide onto which control you are drawing; there are several rules and limitation, like when drawing onto overlapping controls.. – TaW Apr 07 '21 at 08:41
-
[How to use the Paint event to draw shapes at mouse coordinates](https://stackoverflow.com/a/53708936/7444103). Just use the `StartPosition` and `Location` Points instead of drawing Rectangles. – Jimi Apr 07 '21 at 09:27
1 Answers
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.

- 36
- 4