1: 关联一个TreeCtrl控件变量m_treeCtrl,然后定义一个CImageList对象m_imagelist
创建六个ICON图标,ID号为IDI_ICON1~IDI_ICON6,在初始化对话框中添加如下代码:
m_imagelist.Create(16,16,ILC_COLOR,6,6);
m_imagelist.Add(AfxGetApp()->LoadIcon(IDI_ICON1));m_imagelist.Add(AfxGetApp()->LoadIcon(IDI_ICON4));
m_imagelist.Add(AfxGetApp()->LoadIcon(IDI_ICON5));
m_imagelist.Add(AfxGetApp()->LoadIcon(IDI_ICON6));
//显示风格
m_treeCtrl.ModifyStyle(NULL,TVS_HASBUTTONS|TVS_HASLINES|TVS_LINESATROOT|TVS_EDITLABELS);m_treeCtrl.SetImageList(&m_imagelist,LVSIL_NORMAL);
//根结点
HTREEITEM hRootItem=m_treeCtrl.InsertItem(L"中国",1,0,TVI_ROOT);m_treeCtrl.Expand(hRootItem,TVE_EXPAND);//使结点具有扩展性
//添加按钮响应消息,用于添加结点
void CTreeCtrlDlg::OnBnClickedBtnAdd()
{
// TODO: 在此添加控件通知处理程序代码
HTREEITEM hSel=m_treeCtrl.GetSelectedItem();
if(hSel==NULL)
return;
HTREEITEM hSub=m_treeCtrl.InsertItem(_T("新的城市"),hSel);
m_treeCtrl.Expand(hSel,TVE_EXPAND);
m_treeCtrl.EditLabel(hSub);
}
void CTreeCtrlDlg::OnBnClickedBtnDelete()
{
// TODO: 在此添加控件通知处理程序代码
HTREEITEM hSel=m_treeCtrl.GetSelectedItem();
if(hSel==NULL)
return;
if(m_treeCtrl.ItemHasChildren(hSel))
if(MessageBox(L"存在子项,是否一同删除?",L"警告",MB_YESNO)==IDNO)
return;
m_treeCtrl.DeleteItem(hSel);
}