This page looks best with JavaScript enabled

VB.NET - Getting Started with Custom Drawing

 ·   ·  ☕ 2 min read

Here I am going to show some basics of custom drawing in VB.NET.
This is not production-class code, but rather a head start for those assessing whether or not it’s feasible to custom draw anything (result vs effort).
In this sample project, I will highlight all even items of a ListBox with LightGray color. Here is an extract of how it’s done, if you don’t want to download anything.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
Private Shared Sub ListBox1_DrawItem(sender As System.Object, _
                                     e As System.Windows.Forms.DrawItemEventArgs) Handles ListBox1.DrawItem
  'highlight all even items
  If e.Index Mod 2 = 0 Then
    e.Graphics.FillRectangle(Brushes.LightGray, e.Bounds) 'draw custom background
  Else
    e.DrawBackground() 'draw standard background
  End If
  'draw text
  Dim text As String = CType(sender, ListBox).Items(e.Index).ToString()
  Dim textLocation As New System.Drawing.PointF(e.Bounds.X, e.Bounds.Y)
  e.Graphics.DrawString(text, e.Font, Brushes.Black, textLocation)
  e.DrawFocusRectangle()
End Sub

For this to work, you need to have a ListBox dropped on a form and set its property DrawMode to OwnerDrawFixed or OwnerDrawVariable. I used OwnerDrawFixed for simplicity. The other one allows you to have items of variable height. Several notes on the above code:

  • The handler is declared is Shared, which is not common practice, and just to show that it’s not instance dependent. You will probably be using a non-shared handler.
  • DrawItemEventArgs class has a property State of type DrawItemState, which tells whether or not the item is currently Selected, Enabled or other. You may want to differentiate the highlight depending on that in production code. Or add some visual anchors to the item, such as custom icons etc. Keep in mind that not all states are used in all controls, so always refer to documentation when in doubt.

Sample project is attached.


Victor Zakharov
WRITTEN BY
Victor Zakharov
Web Developer (Angular/.NET)