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.
|