CTreeCtrl有几种方式对其子项进行排序
- InsertItem allows to insert the child item alphabetically, when specifying TVI_SORT for hInsertAfter可以实现对插入节点按照字母顺序进行排序,前提是在参数hInsertAfter中指定为TVI_SORT.
- SortChildren performs an alphabetical sorting of the child items of the given parent item in a tree可以实现对对一个父节点的所有子节点以字母顺序进行排序。
- SortChildrenCB performs a sort with a user-defined callback (hence the CB suffix) of the children of the specified item。这种方式,则可以由自己指定规则,按照自己的规则进行排序。
// Sort the item in reverse alphabetical order.
int CALLBACK MyCompareProc(LPARAM lParam1, LPARAM lParam2, LPARAM lParamSort)
{
// lParamSort contains a pointer to the tree control.
// The lParam of an item is just its handle,
// as specified with SetItemData
CTreeCtrl* pmyTreeCtrl = (CTreeCtrl*)lParamSort;
CString strItem1 = pmyTreeCtrl->GetItemText((HTREEITEM)lParam1);
CString strItem2 = pmyTreeCtrl->GetItemText((HTREEITEM)lParam2);
return strItem2.Compare(strItem1);
}
TVSORTCB tvs;
// Sort the tree control's items using my
// callback procedure.
tvs.hParent = TVI_ROOT;
tvs.lpfnCompare = MyCompareProc;
tvs.lParam = (LPARAM)&m_TreeCtrl;
m_TreeCtrl.SortChildrenCB(&tvs);
// Sort the tree control's items using my
// callback procedure.
tvs.hParent = TVI_ROOT;
tvs.lpfnCompare = MyCompareProc;
tvs.lParam = (LPARAM)&m_TreeCtrl;
m_TreeCtrl.SortChildrenCB(&tvs);
特别注意回调函数
<span style="font-size:18px;"><span style="font-family:Microsoft YaHei;"><span class="code-keyword" style="margin: 0px; padding: 0px; border: 0px currentColor; border-image: none; color: blue;">int</span> CALLBACK CompareFunc(LPARAM lParam1, LPARAM lParam2, LPARAM lParamSort);</span></span>
的lparam1和lparam2都是树节点的getitemdata获取的DWORD值,可以将有用的值与该DWORD值绑定,进而根据自己想要排序根据进行排序
。