程序人生

一头犁牛半块田,收也凭天,荒也凭天;粗茶淡饭饱三餐,早也香甜,晚也香甜;布衣得暖胜丝棉,长也可穿,短也可穿;草舍茅屋有几间,行也安然,住也安然;雨过天晴驾一船,鱼在一边,酒在一边;夜归儿女话灯前,今也有言,古也有言;日上三竿我独眠,谁是神仙,我是神仙

  博客园 :: 首页 :: 博问 :: 闪存 :: 新随笔 :: 联系 :: 订阅 订阅 :: 管理 ::




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;

posted on 2004-09-08 10:12  啸天犬  阅读(1048)  评论(1编辑  收藏  举报