TreeView控件添加复选框

Delphi的代码,参考一下吧
首先当然是要在Form加一个TTreeView控件咯。:)

然后在单元的公共uses部分加一个Commctrl单元。

好,接下来要做三件事,
1、在FormCreate事件中
加入如下代码
var
dw: DWORD;
begin
dw := GetWindowLong( TreeView1.Handle, GWL_STYLE);
dw := dw or TVS_CHECKBOXES;
SetWindowLong(TreeView1.Handle, GWL_STYLE , dw);
end;

2、加两个函数
function SetTreeViewNodeChecked(ATreeView: TTreeView;
ATreeNode: TTreeNode; Checked: Boolean): Boolean;

function GetTreeViewNodeChecked(ATreeView: TTreeView;
ATreeNode: TTreeNode): Boolean;

第一个用来设置一个节点的是否被Check
第二个用来取得一个节点的Check状态。

3、就是这两个地实现代码了。

function SetTreeViewNodeChecked(ATreeView: TTreeView;
ATreeNode: TTreeNode; Checked: Boolean): Boolean;
var
tvItem: TTVItem;
begin
tvItem.mask := TVIF_HANDLE or TVIF_STATE;
tvItem.hItem := ATreeNode.ItemId;
tvItem.stateMask := TVIS_STATEIMAGEMASK;

(*Image 1 in the tree-view check box image list is the
unchecked box. Image 2 is the checked box.*)
if Checked then
tvItem.state := IndexToStateImageMask(2) else
tvItem.state := IndexToStateImageMask(1);

Result := TreeView_SetItem(ATreeView.Handle, tvItem);
end;

function GetTreeViewNodeChecked(ATreeView: TTreeView;
ATreeNode: TTreeNode): Boolean;
var
tvItem: TTVItem;
begin
// Prepare to receive the desired information.
tvItem.mask := TVIF_HANDLE or TVIF_STATE;
tvItem.hItem := ATreeNode.ItemId;
tvItem.stateMask := TVIS_STATEIMAGEMASK;

// Request the information.
TreeView_GetItem(ATreeView.Handle, tvItem);

// Return zero if it's not checked, or nonzero otherwise.
Result := Boolean((tvItem.state shr 12) - 1);
end;

posted on 2014-09-17 00:35  云之灵  阅读(2477)  评论(0编辑  收藏  举报