с++ Microsoft MFC 树视图图标

С++ Microsoft MFC TreeView Icons

本文关键字:视图 图标 MFC Microsoft      更新时间:2023-10-16

我通过一篇博客文章编写了 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);
}

图标已添加到资源的文件中。我有错误吗?我有带有下一个文本的消息框:"资源 1"、"资源 2"。

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

图像列表应声明为类成员,以便只要CTreeCtrl需要它,它就保持有效。请注意,m_前缀通常在 MFC 中用于指示"类成员"。

class CLeftView : public CTreeView
{
    CImageList m_tree_imglist;
    ...
};
void CLeftView::OnInitialUpdate()
{
    ...
    //CImageList m_tree_imglist; <- remove
    tc.SetImageList(&m_tree_imglist, TVSIL_NORMAL);
}