MFC TreeCtrl实例

    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_ICON2));
m_imagelist.Add(AfxGetApp()->LoadIcon(IDI_ICON3));

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);
TCHAR *prinny[]={_T("安徽"),_T("江苏"),_T("山东")};
TCHAR *Acity[]={_T("蚌埠"),_T("合肥"),_T("芜湖"),_T("安庆"),_T("淮南")};
TCHAR *Jcity[]={_T("南京"),_T("苏州"),_T("徐州"),_T("常州"),_T("无锡")};
TCHAR *Scity[]={_T("济南"),_T("青岛"),_T("烟台"),_T("威海"),_T("聊城")};
int i,j;
for(i=0;i<3;i++)
{
HTREEITEM hSubItem=m_treeCtrl.InsertItem(prinny[i],hRootItem);
for(j=0;j<5;j++)
{
HTREEITEM hSubItemP;
if(wcscmp(prinny[i],_T("安徽"))==0)
{
hSubItemP=m_treeCtrl.InsertItem(Acity[j],hSubItem);
}
else if(wcscmp(prinny[i],_T("江苏"))==0)
{
hSubItemP=m_treeCtrl.InsertItem(Jcity[j],hSubItem);
}
else if(wcscmp(prinny[i],_T("山东"))==0)
{
hSubItemP=m_treeCtrl.InsertItem(Scity[j],hSubItem);
}
}
m_treeCtrl.Expand(hSubItem,TVE_EXPAND);
}

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


你可能感兴趣的:(C++,MFC,树形控件的用法)