Sunday, November 16, 2008

Setting the Background Color of a TreeView Control

Although disabling a TreeView control is easy (you have to set oTree.Object.Enabled rather than oTree.Enabled), making it appear disabled is a different matter. One way to do it is to set the background color of the control to a disabled-looking color. However, when you try to do that, you'll discover the TreeView doesn't have a BackColor property.

The trick to setting the background color of the TreeView is to use some API calls. Also, you need to set the BackColor of each node. Here's the code to do that. Pass it a reference to the TreeView and the RGB value to use for the color.

lparameters toTree, ;
local lnhWnd, ;
loNode, ;

* Declare some Windows API functions and constants we need.

declare long GetWindowLong in Win32API long hWnd, long nIndex
declare long SetWindowLong in Win32API long hWnd, long nIndex, ;
long dwNewLong
declare SendMessage in Win32API long hWnd, long Msg, long wParam, ;
long lParam
#define GWL_STYLE -16
#define TVM_SETBKCOLOR 4381
#define TVS_HASLINES 2

* Get the TreeView's window handle.

lnhWnd = toTree.hWnd

* Set the BackColor for every node.

for each loNode in toTree.Nodes
loNode.BackColor = tnColor
next loNode

* Set the BackColor for the TreeView's window.

SendMessage(lnhWnd, TVM_SETBKCOLOR, 0, tnColor)

* Get the current style, then temporarily hide lines and redisplay them so
* they'll redraw in the new color.

lnStyle = GetWindowLong(lnhWnd, GWL_STYLE)
SetWindowLong(lnhWnd, GWL_STYLE, bitxor(lnStyle, TVS_HASLINES))
SetWindowLong(lnhWnd, GWL_STYLE, lnStyle)


M Aamir said...

Thanks. It was a great help.


Muhammad Aamir

Doug Hennig said...

Someone posted a comment for this blog entry but I accidentally deleted it. Please repost it so I can answer your question. Thanks.

Anonymous said...

Hi, I know that's an old post but... I read it only in these days.

I'm sorry, the code you show don't seem to work well : the background is coloured but it respect the indentation of every node so the final effect is ugly with the left zone in white background.

Do you think is possible to fix this problem ?

Thank's in advance


Doug Hennig said...

You are right, Alberto. I posted a new blog entry,, that uses a different technique that works better. Thanks!