MFC TreeCtrl traverses all nodes

This example is mainly to find a node in the tree and expand it to select it. Adopt a recursive method to achieve. Main methods used:

CTreeCtrl :: GetChildItem
HTREEITEM GetChildItem (HTREEITEM hItem);
Return value: if successful, return the handle of the child item; otherwise return NULL.

Using recursive thinking, treat each traversed node as the root node, and then traverse the son node in him.
The son node is regarded as the root node again and again, until the real root nodes are traversed, and the whole process is over. It's unclear to see the code at a glance.

Button code

void CForTreeCtrlDlg :: OnBnClickedButton1 () 
{ 
	// TODO: Add control notification handler code 

	UpdateData (TRUE); 

	vector <HTREEITEM> vecItem; 
	HTREEITEM root = treeCtrl.GetRootItem (); 
	// The first layer of root node 
	while (root ! = NULL) { 

		vecItem.push_back (root); 
		root = treeCtrl.GetNextItem (root, TVGN_NEXT); 
	} 
	for (int q = (int) vecItem.size ()-1; q> -1; q--) { 
		func (vecItem [q], m_find); 
	} 

}

 recursive function

void CForTreeCtrlDlg :: func (HTREEITEM root, CString condition) { 
	
	CString itemText = treeCtrl.GetItemText (root); 

	if (itemText.Find (condition)! = -1) { 

		treeCtrl.SelectItem (root); 
		treeCtrl.SetCheck (root, TRUE); 
		treeCtrl.Expand (root, TVM_EXPAND);	 
		return; 
	} 
	// The son node of the root node 
	HTREEITEM A1 = treeCtrl.GetChildItem (root); 

	// The brother node of the son node 
	vector <HTREEITEM> vecItem; 

	while (A1! = NULL) { 

		vecItem.push_back (A1); 
		A1 = treeCtrl.GetNextItem (A1, TVGN_NEXT); 
	} 

	for (int q = (int) vecItem.size ()-1; q> -1; 

		q-- ) { CString itemText = treeCtrl.GetItemText (vecItem [q]); 

		if (itemText.Find (condition)! = -1) {

			treeCtrl.SelectItem (vecItem [q]); 
			treeCtrl.SetCheck (vecItem [q], TRUE); 
			treeCtrl.Expand (vecItem [q], TVM_EXPAND); 
			vecItem.clear (); 
			return; 
		} 
		else { 
			// recursive, son The node is used as the root node to traverse 
			func (vecItem [q], condition); 
		} 
	} 
}

 Building treeCtrl node code

	// TODO: 在此添加额外的初始化代码
	CString root[2] = { TEXT("A"),TEXT("B") };

	for (int i=0;i<2;i++)
	{
		HTREEITEM r =treeCtrl.InsertItem(root[i], NULL);

		CString str;
		for (int j=0;j<3;j++)
		{
			str.Format(TEXT("%s%d"),root[i], j + 1);
			HTREEITEM j1 = treeCtrl.InsertItem(str, r);

			CString str1;
			for (int m = 0; m < 3; m++) {

				str1.Format(TEXT("%s%d%d"),  root[i], j + 1,m+1);
				HTREEITEM m1 = treeCtrl.InsertItem(str1, j1);

				CString str2;
				for (int q = 0; q < 3; q++) {

					str2.Format(TEXT("%s%d%d%d"), root[i], j + 1, m + 1,q+1);
					HTREEITEM q1 = treeCtrl.InsertItem(str2,m1);

					CString str3;
					for (int s = 0; s < 3; s++) {

						str3.Format(TEXT("%s%d%d%d%d"), root[i], j + 1, m + 1, q + 1,s+1);
						HTREEITEM s1 = treeCtrl.InsertItem(str3, q1);
					}
				}
			}
		}
	}

 

Guess you like

Origin www.cnblogs.com/HelloQLQ/p/12678753.html