Introduction
This article shows the owner draw technique for a TreeView
using Visual Basic .NET to draw some portions of the text of the nodes in bold font, as shown in the image.
Background
The owner draw technique for Windows Common Controls is well documented in the following MSDN article: Customizing a Control's Appearance Using Custom Draw&, which I recommend to read. The article explains the notification messages, the paint cycles and drawing stages, and provides a C++ example, so I won't repeat it here.
Using the code
A TreeNodeEx
class (derived from TreeNode
) is provided in the source code, which allows you to specify in the constructor the node text, the initial text position that will use the bold font, and the length of the bold text.
A helper function like this is provided to add nodes to a TreeView
:
Private Function AddNodeToTreeView(ByVal colNodes As TreeNodeCollection, _
ByVal sText As String, ByVal iBoldTextInitialPosition As Integer, _
ByVal iBoldTextLength As Integer) As TreeNodeEx
Dim objTreeNodeEx As TreeNodeEx
objTreeNodeEx = New TreeNodeEx(sText, _
iBoldTextInitialPosition, iBoldTextLength)
colNodes.Add(objTreeNodeEx)
Return objTreeNodeEx
End Function
A TreeViewEx
class (derived from TreeView
) is provided too. This class performs the owner draw with the tree nodes. The class is used as follows:
Private m_ctlTreeViewEx As TreeViewEx
Private Sub Form1_Load(ByVal sender As System.Object, _
ByVal e As System.EventArgs) Handles MyBase.Load
Dim objRootTreeNodeEx As TreeNodeEx
m_ctlTreeViewEx = New TreeViewEx()
Me.Controls.Add(m_ctlTreeViewEx)
m_ctlTreeViewEx.Left = 0
m_ctlTreeViewEx.Top = 0
m_ctlTreeViewEx.Dock = DockStyle.Fill
objRootTreeNodeEx = AddNodeToTreeView(m_ctlTreeViewEx.Nodes, _
"This is the first node", 12, 5)
AddNodeToTreeView(objRootTreeNodeEx.Nodes, "The second node", 4, 6)
AddNodeToTreeView(objRootTreeNodeEx.Nodes, "Third node", 0, 5)
AddNodeToTreeView(objRootTreeNodeEx.Nodes, "Node 4", 5, 1)
AddNodeToTreeView(objRootTreeNodeEx.Nodes, "Last node", -1, 0)
objRootTreeNodeEx.Expand()
End Sub
Points of Interest
There are some points of interest in the source code:
History
- 24-May-2005. Initial version.