An alternative to using C#'s native drawing facility which is based on using the Paint Event, is to get the Visual Basic PowerPacks "Line and Shape" controls: [
^].
Using those tools, you do not need to explicitly concern yourself with pens, brushes, graphic objects, etc.
There's a tutorial on how to use them here: [
^].
Here's an example of code in C# that uses the VB PowerPack LineShape facility to draw a red diagonal line 4 pixels in width from the top, left to bottom, right of a Form of size 900,600:
using Microsoft.VisualBasic.PowerPacks;
ShapeContainer canvas = new ShapeContainer();
canvas.Parent = this;
LineShape aLine = new LineShape(0, 0, 900, 600);
aLine.Parent = canvas;
aLine.BorderStyle = System.Drawing.Drawing2D.DashStyle.Solid;
aLine.BorderWidth = 4;
aLine.BorderColor = Color.Red;
aLine.Click += aLine_Click;
By defining a Click EventHandler:
private void aLine_Click(object sender, EventArgs e)
{
MessageBox.Show("aLine clicked");
}
We now have a "clickable" line, and a line you could, if necessary, make movable by some trickery (the techniques commonly used to make other Controls on a Form movable don't quite work with the line and shape objects).
Note that the Line is always drawn on the Form
behind all other Controls: calling BringToFront() on it will not cause an error, but will have no effect.
Statements have been made on CodeProject that you cannot successfully inherit from a Form or UserControl which has lines, or shapes, created with the VB PowerPack Tools, and have the lines, or shapes, "work." I have verified that you can, indeed, inherit from a UserControl using the VB Tools, and the lines and shapes "work" in the inheriting Control.
You might take a look at Erdal Halici's 2013 article here on CP if you wish to go deeply into drawing shapes in .NET: [
^].
Whether the "cost" (memory, performance) of using the VB tools for drawing in your C# application is
acceptable is something only you can decide.
I would choose to use the VB Tools only when I wanted persistent graphic objects the user could
interact with at run-time.