CodeGuru Home VC++ / MFC / C++ .NET / C# Visual Basic VB Forums Developer.com
Results 1 to 1 of 1
  1. #1
    Join Date
    Jun 2001
    Location
    Switzerland
    Posts
    4,443

    MFC Tree Control: How to add icons to a tree control?

    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.

    Code:
    CImageList m_tree_imglist;
    In 'OnInitDialog()' create the image list, and add the icons:

    Code:
    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

    Code:
       
    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

    Code:
    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 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;
    }
    Last edited by Andreas Masur; January 31st, 2006 at 05:05 PM.

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  





Click Here to Expand Forum to Full Width

Featured