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.
In 'OnInitDialog()' create the image list, and add the icons:Code:CImageList m_tree_imglist;
Attach the image list to the tree controlCode: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));
When you add an item to the tree, specify the zero based index of the image to be usedCode:m_tree.SetImageList(&m_tree_imglist, TVSIL_NORMAL);
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.Code:m_tree.InsertItem("Item text", nImage, nImage, hParent, hInsertAfter);
You can use other approaches if you aim to obtain different effects. See MSDN 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:
Code: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; }




Reply With Quote