VC中Tree Control的使用
邵盛松 2010年11月29日星期一
下载地址 http://download.csdn.net/source/2868628
一 Tree Control的初始化
HTREEITEM hTreeItemParent=NULL;
HTREEITEM hTreeItemChild=NULL;
CString strParentData=L"";
CString strChildData=L"";
for (int i=1;i<5;i++)
{
strParentData.Format(L"%d-Parent",i);
hTreeItemParent=m_Tree_ctlDemo.InsertItem(strParentData);
m_Tree_ctlDemo.SetItemData(hTreeItemParent,i);
strChildData.Format(L"%d-Child",i*100);
hTreeItemChild=m_Tree_ctlDemo.InsertItem(strChildData,hTreeItemParent);
m_Tree_ctlDemo.SetItemData(hTreeItemChild,i*100);
}
二 Tree Control的单击响应
void CTreeDemoDlg::OnNMClickTree(NMHDR *pNMHDR, LRESULT *pResult)
{
// TODO: 在此添加控件通知处理程序代码
CPoint pt;
GetCursorPos(&pt);
m_Tree_ctlDemo.ScreenToClient(&pt);
CString strAll=L"";
UINT nFlag = 0;
HTREEITEM hItem = m_Tree_ctlDemo.HitTest(pt, &nFlag);
if( NULL != hItem )
{
m_Tree_ctlDemo.SelectItem(hItem);
CString strTemp=m_Tree_ctlDemo.GetItemText(hItem);
DWORD nID=m_Tree_ctlDemo.GetItemData(hItem);
strAll.Format(L"%d,%s",nID,strTemp);
m_Static_strTree=strAll;
UpdateData(FALSE);
}
*pResult = 0;
}
三只遍历根节点
void CTreeDemoDlg::OnBnClickedButtonRoot()
{
// TODO: 在此添加控件通知处理程序代码
HTREEITEM hTreeItemRoot=NULL;
CString strItem=L"";
if (hTreeItemRoot=m_Tree_ctlDemo.GetRootItem())
{
while (hTreeItemRoot!=NULL)
{
strItem=m_Tree_ctlDemo.GetItemText(hTreeItemRoot);
AfxMessageBox(strItem);
hTreeItemRoot=m_Tree_ctlDemo.GetNextSiblingItem(hTreeItemRoot);
}
}
}
四非递归遍历具有两层目录的节点
void CTreeDemoDlg::OnBnClickedButtonAll()
{
// TODO: 在此添加控件通知处理程序代码
HTREEITEM hTreeItemRoot=NULL;
HTREEITEM hTreeItemChild=NULL;
CString strParentItem=L"";
CString strChildItem=L"";
CString strParentPrompt=L"";
CString strChildPrompt=L"";
DWORD nParent=0;
DWORD nChild=0;
if (hTreeItemRoot=m_Tree_ctlDemo.GetRootItem())
{
while (hTreeItemRoot!=NULL)
{
strParentItem=m_Tree_ctlDemo.GetItemText(hTreeItemRoot);
nParent=m_Tree_ctlDemo.GetItemData(hTreeItemRoot);
strParentPrompt.Format(L"%d,%s",nParent,strParentItem);
AfxMessageBox(strParentPrompt);
if (m_Tree_ctlDemo.ItemHasChildren(hTreeItemRoot))
{
hTreeItemChild = m_Tree_ctlDemo.GetChildItem(hTreeItemRoot);
while (hTreeItemChild != NULL)
{
strChildItem=m_Tree_ctlDemo.GetItemText(hTreeItemChild);
nChild=m_Tree_ctlDemo.GetItemData(hTreeItemChild);
strChildPrompt.Format(L"%d,%s",nChild,strChildItem);
AfxMessageBox(strChildPrompt);
hTreeItemChild= m_Tree_ctlDemo.GetNextSiblingItem(hTreeItemChild);
}
}
hTreeItemRoot=m_Tree_ctlDemo.GetNextSiblingItem(hTreeItemRoot);
}
}
}
六递归遍历所有节点
void CTreeDemoDlg::RecursiveTree(HTREEITEM hTreeItemRoot)
{
HTREEITEM hTreeItemNext = NULL;
HTREEITEM hTreeItemChild = NULL;
if(hTreeItemRoot == NULL)
return;
AfxMessageBox(m_Tree_ctlDemo.GetItemText(hTreeItemRoot));
hTreeItemChild = m_Tree_ctlDemo.GetChildItem(hTreeItemRoot);
RecursiveTree(hTreeItemChild);
hTreeItemNext=m_Tree_ctlDemo.GetNextItem(hTreeItemRoot,TVGN_NEXT);
RecursiveTree(hTreeItemNext);
}
以上程序在 VC++2005 Unicode字符集下调试通过