С++ Microsoft MFC TreeView 图标

С++ Microsoft MFC TreeView Icons

我在一篇博文中写了一段TreeView控件的代码。我正在尝试将图标添加到列表项。但是图标没有渲染。 我有下一个代码:

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);
}

资源文件中添加了图标。我有错误吗?我有带有下一个文本的消息框:"resource1"、"resource2".

m_tree_imglist 在堆栈上声明,此图像列表在 OnInitialUpdate 退出后被销毁,因此 CTreeCtrl 不再有图像列表。

图像列表应该声明为 class 成员,这样只要 CTreeCtrl 需要它,它就一直有效。注意m_前缀在MFC中通常用来表示"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);
}