1.首先建立一个基于Dialog的Tree_Test工程,删除对话框中多余控件并添加一个Tree控件,并注意修改Tree控件属性Has Buttons 和Has Lines 设为TRUE;
2.为上面的树形控件添加一个变量:CTreeCtrl m_tree;
3.在OnInitDialog()中添加如下代码:
//TODO:在此添加额外初始化代码:
/*++++++++++++++++++++++++++++++++++++++++++++++++*/
/*假设m_tree为一个CTreeCtrl对象,而且该窗口已经创建*/
HTREEITEM hItem,hSubItem,hSubItem2;
hItem = m_tree.InsertItem("Parent1",TVI_ROOT);
//在根结点上添加Parent1
hSubItem = m_tree.InsertItem("Child1_1",hItem);
//在Parent1上添加一个子结点
hSubItem2 = m_tree.InsertItem("Baby One more Kiss",hSubItem);
hSubItem = m_tree.InsertItem("Child1_2",hItem,hSubItem);
//在Parent1上添加一个子结点,排在Child1_1后面
hSubItem = m_tree.InsertItem("Child1_3",hItem,hSubItem);
hItem = m_tree.InsertItem("Parent2",TVI_ROOT,hItem);
hItem = m_tree.InsertItem("Parent3",TVI_ROOT,hItem);
/*++++++++++++++++++++++++++++++++++++++++++++++++*/
4.编译运行可得如下结果:
6.在Tree_TestDlg.h头文件中添加一个变量:CImageList m_list;
7.之后再在OnInitDialog()中增添如下代码:
//m_list 为CImageList对象要声明为对话框的成员变量,在对话框头文件中添加代码CImageList m_list;
//IDB_TREE 为!!!!16*16!!!!的位图在Resource View中添加
m_list.Create(IDB_TREE,16,1,ILC_COLOR8);
//注释:IDB_TREE是图标的ID号.
m_tree.SetImageList(&m_list,TVSIL_NORMAL);
m_tree.SetTextColor(RGB(200,0,200));//设置树形控件中的文字颜色
8.最终效果图: