Este artículo ilustra cómo cambiar el color de fondo de un TreeView. Para ello necesitamos la versión 4.70 o superior de la librería comctl32.dll. Esta versión se consigue instalando el Internet Explorer 4.0. Según Microsoft esta librería no podemos distribuirla, por lo que habrá que instalar IE 4.0 en los ordenadores en los que necesitemos usarla.
NOTA: Si empleas 256 colores o menos, usando un fondo de color "tramado" (dithered) se producen resultados no satisfactorios porque el TreeView y muchos otros controles de Windows no pueden escribir texto sobre un fondo tramado. Cambia el último parámetro de la llamada a SendMessage a RGB(200, 255, 200) para ver este efecto.
Crea un formulario con un TreeView y botón.
En la sección de declaraciones del formulario:
Private Declare Function SendMessage Lib "User32" Alias "SendMessageA" (ByVal hWnd As Long, ByVal wMsg As Long, ByVal wParam As Long, lParam As Long) As Long
Private Declare Function GetWindowLong Lib "User32" Alias "GetWindowLongA" (ByVal hWnd As Long, ByVal nIndex As Long) As Long
Private Declare Function SetWindowLong Lib "User32" Alias "SetWindowLongA" (ByVal hWnd As Long, ByVal nIndex As Long, ByVal dwNewLong As Long) As Long
Private Const GWL_STYLE = -16&
Private Const TVM_SETBKCOLOR = 4381&
Private Const TVM_GETBKCOLOR = 4383&
Private Const TVS_HASLINES = 2&
En el evento Form_Load() :
Dim nodX As Node
Set nodX = TreeView1.Nodes.Add(, , "R", "Root")
Set nodX = TreeView1.Nodes.Add("R", tvwChild, "C1", "Child 1")
Set nodX = TreeView1.Nodes.Add("R", tvwChild, "C2", "Child 2")
Set nodX = TreeView1.Nodes.Add("R", tvwChild, "C3", "Child 3")
Set nodX = TreeView1.Nodes.Add("R", tvwChild, "C4", "Child 4")
nodX.EnsureVisible
TreeView1.style = tvwTreelinesText ' Style 4.
TreeView1.BorderStyle = vbFixedSingle
En el evento click del botón :
Dim lngStyle As Long
Call SendMessage(TreeView1.hWnd, TVM_SETBKCOLOR, 0, ByVal RGB(255, 0, 0)) 'cambiar el fondo a rojo
'resetar el estilo para que se vean correctamente las líneas
lngStyle = GetWindowLong(TreeView1.hWnd, GWL_STYLE)
Call SetWindowLong(TreeView1.hWnd, GWL_STYLE, lngStyle - TVS_HASLINES)
Call SetWindowLong(TreeView1.hWnd, GWL_STYLE, lngStyle)