Click to See Complete Forum and Search --> : MFC Tree Controll: How to add icons to a tree control?


Gabriel Fleseriu
February 14th, 2003, 09:13 AM
Q: How to add icons to a tree control?

A: Add a number of icons to your projects resources (say 'IDI_ICON1' ... 'IDI_ICON4', 16x16 pixels).

Add a member variable of the type 'CImageList' to dialog class that hosts your tree control.


CImageList m_tree_imglist;


In 'OnInitDialog()' create the image list, and add the icons:


m_tree_imglist.Create(16, 16, ILC_MASK, 0, 4);
m_tree_imglist.Add(AfxGetApp()->LoadIcon(IDI_ICON1));
m_tree_imglist.Add(AfxGetApp()->LoadIcon(IDI_ICON2));
m_tree_imglist.Add(AfxGetApp()->LoadIcon(IDI_ICON3));
m_tree_imglist.Add(AfxGetApp()->LoadIcon(IDI_ICON4));

Attach the image list to the tree control


m_tree.SetImageList(&m_tree_imglist, TVSIL_NORMAL);

When you add an item to the tree, specify the zero based index of the image to be used


m_tree.InsertItem("Item text",
nImage, nImage,
hParent,
hInsertAfter);

Remarks: using icons and the 'ILC_MASK' style for the image list ensures that you don't have to bother about the look of the image when the item is selected or not selected. Simply use a transparent background for the icon and use the same image index for nImage and nSelectedImage when you add the item.

You can use other approaches if you aim to obtain different effects. See MSDN (http:msdn.microsoft.com) for details.

If you want an item to show different images when it is expanded and collapsed, handle the 'TVN_ITEMEXPANDED' message and use 'SetItemImage(hItem, nImage, nImage)' to set the items image according to its state:


void CYourDialog::OnItemexpandedTree(NMHDR* pNMHDR, LRESULT* pResult)
{
NM_TREEVIEW* pNMTreeView = (NM_TREEVIEW*) pNMHDR;
HTREEITEM hItem = pNMTreeView->itemNew.hItem;
UINT state = pNMTreeView->itemNew.state;
UINT action = pNMTreeView->action;

if(action & TVE_COLLAPSE)
{
m_tree.SetItemImage(hItem, nImageCollapsed, nImageCollapsed);
}

if(action & TVE_EXPAND)
{
m_tree.SetItemImage(hItem, nImageExpanded, nImageExpanded);
}

*pResult = 0;
}

<br>