本例效果圖:
unit Unit1;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, ComCtrls, StdCtrls;
type
TForm1 = class(TForm)
TreeView1: TTreeVIEw;
Button1: TButton;
Button2: TButton;
Button3: TButton;
procedure FormCreate(Sender: TObject);
procedure Button1Click(Sender: TObject);
procedure Button2Click(Sender: TObject);
procedure Button3Click(Sender: TObject);
end;
var
Form1: TForm1;
implementation
{$R *.dfm}
uses CommCtrl;
//讓 TreeVIEw 帶有復選框
procedure TForm1.FormCreate(Sender: TObject);
var
H: HWND;
begin
H := TreeVIEw1.Handle;
SetWindowLong(H, GWL_STYLE, GetWindowLong(H, GWL_STYLE) or TVS_CHECKBOXES);
{下面的代碼只是給 TreeVIEw 添加內容}
with TreeVIEw1 do
begin
Align := alLeft;
Items.Add(nil, 'AAA');
Items.Add(nil, 'BBB');
Items.Add(nil, 'CCC');
Items.AddChild(Items[2], '111');
Items.AddChild(Items[2], '222');
Items.AddChild(Items[2], '333');
end;
end;
//列舉帶有復選框的項
procedure TForm1.Button1Click(Sender: TObject);
var
Node: TTreeNode;
TVI: TTVItem;
begin
for Node in TreeVIEw1.Items do
begin
TVI.mask := TVIF_STATE;
TVI.hItem := Node.ItemId;
TreeView_GetItem(TreeVIEw1.Handle, TVI);
if TVI.state and $2000 = $2000 then
ShowMessage(Node.Text);
end;
end;
//取消所有選中(這是後來補充的, 所以效果圖上沒有)
procedure TForm1.Button2Click(Sender: TObject);
var
Node: TTreeNode;
TVI: TTVItem;
begin
for Node in TreeVIEw1.Items do
begin
TVI.mask := TVIF_STATE;
TVI.hItem := Node.ItemId;
TVI.stateMask := TVIS_STATEIMAGEMASK;
TVI.state := $2000 shr 1;
TreeView_SetItem(TreeVIEw1.Handle, TVI);
end;
end;
//選中所有(這是後來補充的, 所以效果圖上沒有)
procedure TForm1.Button3Click(Sender: TObject);
var
Node: TTreeNode;
TVI: TTVItem;
begin
for Node in TreeVIEw1.Items do
begin
TVI.mask := TVIF_STATE;
TVI.hItem := Node.ItemId;
TVI.stateMask := TVIS_STATEIMAGEMASK;
TVI.state := $2000;
TreeView_SetItem(TreeVIEw1.Handle, TVI);
end;
end;
end.