Visual Basic

How To Draw A Line In Visual Basic

To draw a line in Visual Basic Windows Forms, handle the form’s Paint event and call e.Graphics.DrawLine with a pen and two endpoints. The pen controls the colour, thickness and pattern. Keeping the drawing in Paint lets Windows redraw the line when the form needs.

Which licences fit your PC setup?

Prices are an AUD snapshot, not a live quote. Confirm variant and total on the listing.

Set up a Windows Forms drawing surface

These instructions use Visual Basic .NET and Windows Forms. They apply to drawing on a Form, Panel or PictureBox; other application frameworks use different drawing APIs.

Start with a Visual Basic Windows Forms project in Visual Studio. Use the form itself for your first line so there is no additional control to configure. If the project cannot open or initialise, resolve that first using the guide to the Visual Basic environment could not be initialised.

A Graphics object supplies the drawing methods, while a Pen supplies the line’s appearance. In a Paint handler, use the Graphics object provided by e.Graphics. Microsoft’s Windows Forms line-drawing example uses this approach and advises disposing of pens you create.

Draw your first line in the Paint event

  1. Open the form’s code file. Ensure Imports System.Drawing and Imports System.Windows.Forms appear above the form class if those namespaces are not already imported by the project.
  2. Add the following handler inside the form class, outside any existing procedure. If you already have a Paint handler, put the drawing statements in that handler instead.
  3. Run the application. A red diagonal line should appear between the specified coordinates.
  4. Minimise and restore the window to check that the line is drawn again when the form repaints.

Private Sub Form1_Paint(sender As Object, e As PaintEventArgs) Handles MyBase.Paint

    Using linePen As New Pen(Color.Red, 2)

        e.Graphics.DrawLine(linePen, 10, 10, 100, 100)

    End Using

End Sub

The arguments after linePen are x1, y1, x2 and y2: the starting horizontal and vertical coordinates, followed by the ending coordinates. This example runs from (10, 10) to (100, 100). The Using block disposes of the custom pen when drawing finishes. Leave the event-supplied e.Graphics object for Windows Forms to manage.

Choose coordinates for horizontal, vertical or diagonal lines

With the default drawing settings, coordinates start at the top-left of the drawing surface. Increasing x moves right; increasing y moves down. Use equal y values for a horizontal line, equal x values for a vertical line, and different values for both to make a diagonal.

The coordinates belong to the control being painted. If you move the drawing to a PictureBox, handle that PictureBox’s Paint event and measure the endpoints within its client area. The PictureBox’s position on the form is not the starting point inside it.

Keep the line visible when the window repaints

Drawing directly from a button click with CreateGraphics can produce a line that disappears after the window repaints. Store the information needed to draw the line, then render it in Paint.

For a movable line, keep startPoint and endPoint as fields in the form class. Update those fields when input changes, then call Me.Invalidate(). In Paint, use e.Graphics.DrawLine(linePen, startPoint, endPoint) inside the Using block.

Invalidate requests a repaint; it does not draw immediately. Avoid calling it unconditionally from inside Paint, which can cause repeated repainting. Microsoft’s PaintEventArgs.Graphics documentation shows the relationship between stored coordinates, mouse events and repainting.

Change the colour, thickness and dash pattern

In the first example, Color.Red selects the colour and 2 sets the pen width. Change those constructor arguments to adjust the line. For a dashed line, add this statement inside the Using block before DrawLine:

linePen.DashStyle = System.Drawing.Drawing2D.DashStyle.Dash

Use DashStyle.Dot for dots, or DashDot and DashDotDot for mixed patterns. Set these properties on a pen you create, rather than changing shared pens such as Pens.Black.

Define a custom pattern with DashPattern

For a repeating custom pattern, replace the DashStyle assignment with:

linePen.DashPattern = New Single() {3, 2}

The values alternate between dash and gap lengths, measured as multiples of the pen width. Here, each dash is three pen widths long and each gap is two pen widths long. They are not fixed pixel lengths. Use DashPattern for this setting; CompoundArray controls parallel bands across a pen’s stroke. See Microsoft’s custom dashed-line example for the scaling behaviour.

Use mouse input to position the line

Once the fixed line works, use mouse events to let someone drag its endpoints. Keep all mouse and Paint handlers attached to the same drawing control.

  1. Declare startPoint and endPoint as Point fields, plus Boolean fields for dragging and whether a line exists.
  2. In MouseDown, accept the left button only. Set both points to e.Location, mark the line as present and set dragging to True.
  3. In MouseMove, update endPoint only while dragging is True, then invalidate the drawing control.
  4. In MouseUp, finish only an active left-button drag. Save the final e.Location, set dragging to False and invalidate again.
  5. In Paint, draw from the stored points only when a line exists.

This approach stores one line, so a new drag replaces the previous one. To retain several lines, store each pair of endpoints in a collection and redraw that collection during Paint. Event handlers respond to mouse input without a polling loop. For separate tasks that need conditional repetition, the Visual Basic Do While guide explains that control structure.

Refine the line’s appearance

For smoother diagonal edges, set e.Graphics.SmoothingMode to System.Drawing.Drawing2D.SmoothingMode.AntiAlias before drawing. Compare the result at the size your application actually uses.

Set the pen’s StartCap and EndCap to System.Drawing.Drawing2D.LineCap.Round for rounded ends. LineJoin affects corners in connected paths or polylines; it has no visible role in a single isolated DrawLine call.

A LinearGradientBrush can supply a colour transition when passed to a Pen constructor. If you add one, dispose of both the custom pen and brush with Using blocks.

Run the basic Paint example now, change one endpoint, and restore the window after minimising it. Once the line redraws correctly, add one styling option at a time. For further language topics, browse the Visual Basic guides.

Other editions for separate workloads

Other editions for separate workloads; prices in AUD, confirm the total on the listing.

How to check this worked

  1. Open Settings, System, Activation and confirm the edition shown.
  2. Enter the key and run activation; expect a green tick within a minute.
  3. Reboot and re-check activation survives the restart.

FAQ

What else should you know before buying?

What do I need before starting?
Read the requirements and confirm the edition first; the steps assume the machine is compatible.
How do I know the licence is genuine?
Activate on Microsoft's servers and check Settings, System, Activation. A working activation is the test.
Is this a subscription?
Keys sold here are one-time lifetime licences. Microsoft 365 plans are billed by Microsoft instead.
What if the key fails?
Email hi@ms.codes with the order number and a screenshot. Replacement or refund applies within 30 days.

Check who prepared and reviewed this guide

Written by
MS.Codes editorial
Reviewed by
Support team

Last verified: (source review; see test status above).

Recent Post