2

I have written a code of the TreeView Control by a blog article. I am trying to add icons to list items. But icons are no rendered. I have a next code:

void CLeftView::OnInitialUpdate()
{
    CTreeView::OnInitialUpdate();

    // TODO: Add items by GetTreeCtrl().

    HICON hi = NULL;
    hi = AfxGetApp()->LoadIcon(MAKEINTRESOURCE(IDI_ICON1));
    if (hi != NULL)
    {
        MessageBox(NULL, L"resource1");
    }
    else MessageBox(NULL, L"Not resource1");
    HICON lo = NULL;
    lo = AfxGetApp()->LoadIcon(MAKEINTRESOURCE(IDI_ICON2));
    if (lo != NULL)
    {
        MessageBox(NULL, L"resource2");
    }
    else MessageBox(NULL, L"Not resource2");

    CImageList m_tree_imglist;
    CTreeCtrl & tc = CTreeView::GetTreeCtrl();

    m_tree_imglist.Create(16, 16, ILC_COLOR32 | ILC_MASK, 0, 2);

    m_tree_imglist.Add(hi);
    m_tree_imglist.Add(lo);


    tc.SetImageList(&m_tree_imglist, TVSIL_NORMAL);

    HTREEITEM hItem;
    hItem = tc.InsertItem(L"Fonts", 0, 0, TVI_ROOT);
    tc.InsertItem(L"Arial", 0, 0, hItem);
    tc.InsertItem(L"Times", 0, 0, hItem);
    tc.Expand(hItem, TVE_EXPAND);
}

Icons have added to resource's files. There's do I have a bug? I have message boxes with a next text: "resource1", "resource2".

Barmak Shemirani
  • 30,904
  • 6
  • 40
  • 77
HailToTheVictor
  • 388
  • 2
  • 8
  • 28
  • For a dirty and fast solution, detach your local variable m_treee_imgList.Detach() before the funtion ends. However a better an right solution is to declare the variable m_treee_imgList as class member as Barmak shows. – Tom Tom Mar 25 '19 at 12:12

1 Answers1

4

m_tree_imglist is declared on stack, this image list is destroyed after OnInitialUpdate exits, so CTreeCtrl no longer has an image list.

Image list should be declared as class member instead, so that it remains valid as long as CTreeCtrl needs it. Note the m_ prefix is usually used in MFC to indicate "class member".

class CLeftView : public CTreeView
{
    CImageList m_tree_imglist;
    ...
};

void CLeftView::OnInitialUpdate()
{
    ...
    //CImageList m_tree_imglist; <- remove
    tc.SetImageList(&m_tree_imglist, TVSIL_NORMAL);
}
Barmak Shemirani
  • 30,904
  • 6
  • 40
  • 77