uses CommCtrl;
function TreeNodeGetChecked(mTreeNode: TTreeNode): Boolean;
var
vTVItem: TTVItem;
begin
Result := False;
if not Assigned(mTreeNode) or not Assigned(mTreeNode.TreeView) then Exit;
vTVItem.mask := TVIF_STATE;
vTVItem.hItem := mTreeNode.ItemId;
if TreeView_GetItem(mTreeNode.TreeView.Handle, vTVItem) then
Result := (vTVItem.State and IndexToStateImageMask(2)) > 0; //0: None 1: False 2: True
end; { TreeNodeGetChecked }
function TreeNodeSetChecked(mTreeNode: TTreeNode; mChecked: Boolean): Boolean;
var
vTVItem: TTVItem;
begin
Result := False;
if not Assigned(mTreeNode) or not Assigned(mTreeNode.TreeView) then Exit;
vTVItem.mask := TVIF_STATE;
vTVItem.hItem := mTreeNode.ItemId;
TreeView_GetItem(mTreeNode.TreeView.Handle, vTVItem);
if not TreeView_GetItem(mTreeNode.TreeView.Handle, vTVItem) then Exit;
vTVItem.stateMask := TVIS_STATEIMAGEMASK;
vTVItem.state := IndexToStateImageMask(Succ(Ord(mChecked)));
Result := TreeView_SetItem(mTreeNode.TreeView.Handle, vTVItem);
end; { TreeNodeSetChecked }
procedure TForm1.FormCreate(Sender: TObject);
begin
SetWindowLong(TreeView1.Handle, GWL_STYLE,
GetWindowLong(TreeView1.Handle, GWL_STYLE) or TVS_CHECKBOXES);
end;
procedure TForm1.TreeView1MouseDown(Sender: TObject; Button: TMouseButton;
Shift: TShiftState; X, Y: Integer);
procedure pSelect(mTreeNode: TTreeNode; mChecked: Boolean);
var
I: Integer;
begin
TreeNodeSetChecked(mTreeNode, mChecked);
for I := 0 to mTreeNode.Count - 1 do pSelect(mTreeNode[I], mChecked);
end;
procedure pSelectYes(mTreeNode: TTreeNode);
begin
while Assigned(mTreeNode.Parent) and
not TreeNodeGetChecked(mTreeNode.Parent) do begin
TreeNodeSetChecked(mTreeNode.Parent, True);
mTreeNode := mTreeNode.Parent;
end;
end;
procedure pSelectNo(mTreeNode: TTreeNode);
var
I: Integer;
begin
if Assigned(mTreeNode.Parent) and TreeNodeGetChecked(mTreeNode.Parent) then begin
for I := 0 to mTreeNode.Parent.Count - 1 do
if TreeNodeGetChecked(mTreeNode.Parent[I]) then Exit;
TreeNodeSetChecked(mTreeNode.Parent, False);
pSelectNo(mTreeNode.Parent);
end;
end;
var
vTreeNode: TTreeNode;
begin
if not (htOnStateIcon in TTreeView(Sender).GetHitTestInfoAt(X, Y)) then Exit;
vTreeNode := TTreeView(Sender).GetNodeAt(X, Y);
pSelect(vTreeNode, TreeNodeGetChecked(vTreeNode));
if not TreeNodeGetChecked(vTreeNode) then
pSelectNo(vTreeNode)
else pSelectYes(vTreeNode);
end;