Поиск Item’а в TreeView
Поиск Item’а в TreeView
Поиск Item'а в TreeView (how to find an item in a tree control via its label) the "tree view" common control does not have any built-in method for searching the entire tree, or for selecting an item contained within the tree when given a specific item label. this article provides code that returns the location of any item in a tree when given a specific label to search for. the getitembyname() function takes the window handle of the tree control, htreeitem, which points to the item in the tree to start searching and a string for which to search. unit unit1; interface uses windows, messages, sysutils, classes, graphics, controls, forms, dialogs, stdctrls, comctrls; type tform1 = class(tform) button1: tbutton; treeview1: ttreeview; procedure button1click(sender: tobject); private { private declarations } public { public declarations } end; var form1: tform1; implementation {$r *.dfm} uses commctrl; // note: if you have items with more than 50 characters // of text, you'll need to increase this value. const maxtextlen=50; function getitembyname(wnd : hwnd; hitem : htreeitem; szitemname : lpctstr) : htreeitem ; var szbuffer: array [0..maxtextlen+1] of char; item : ttvitem; hitemfound, hitemchild : htreeitem; begin // if hitem is null, start search from root item. if (hitem = nil) then hitem := htreeitem(sendmessage(wnd, tvm_getnextitem, tvgn_root, 0)); while (hitem <> nil) do begin item.hitem := hitem; item.mask := tvif_text or tvif_children; item.psztext := szbuffer; item.cchtextmax := maxtextlen; sendmessage(wnd, tvm_getitem, 0, longint(@item)); // did we find it? if (lstrcmp(szbuffer, szitemname) = 0) then begin result := hitem; exit; end; // check whether we have child items. if (item.cchildren > 0) then begin // recursively traverse child items. hitemchild := htreeitem(sendmessage(wnd, tvm_getnextitem, tvgn_child, longint(hitem))); hitemfound := getitembyname(wnd, hitemchild, szitemname); // did we find it? if (hitemfound <> nil) then begin result := hitemfound; exit; end; end; // go to next sibling item. hitem := htreeitem(sendmessage(wnd, tvm_getnextitem, tvgn_next, lparam(hitem))); end; // not found. result := nil; end; procedure tform1.button1click(sender: tobject); var hitem : htreeitem; begin hitem := getitembyname(treeview1.handle, nil, 'serge'); if (hitem <> nil) then begin treeview1.setfocus; sendmessage(treeview1.handle, tvm_selectitem, tvgn_caret, longint(hitem)); end; end; end.