How to: Draw a Line on a Windows Form

This example draws a line on a form.

Example

Dim myPen As New System.Drawing.Pen(System.Drawing.Color.Red)
Dim formGraphics As System.Drawing.Graphics
formGraphics = Me.CreateGraphics()
formGraphics.DrawLine(myPen, 0, 0, 200, 200)
myPen.Dispose()
formGraphics.Dispose()
System.Drawing.Pen myPen = new System.Drawing.Pen(System.Drawing.Color.Red);
System.Drawing.Graphics formGraphics;
formGraphics = this.CreateGraphics();
formGraphics.DrawLine(myPen, 0, 0, 200, 200);
myPen.Dispose();
formGraphics.Dispose();
System::Drawing::Pen^ myPen =
    gcnew System::Drawing::Pen(System::Drawing::Color::Red);
System::Drawing::Graphics^ formGraphics;
formGraphics = this->CreateGraphics();
formGraphics->DrawLine(myPen, 0, 0, 200, 200);
delete myPen;
delete formGraphics;

Compiling the Code

You cannot call this method in the Load event handler. The drawn content will not be redrawn if the form is resized or obscured by another form. To make your content automatically repaint, you should override the OnPaint method.

Robust Programming

You should always call Dispose on any objects that consume system resources, such as Pen and Graphics objects.

See Also

Reference

DrawLine

OnPaint

Other Resources

Getting Started with Graphics Programming

Using a Pen to Draw Lines and Shapes

Graphics and Drawing in Windows Forms