void __fastcall TForm1::FormCreate(TObject *Sender)
{
SetWindowLong(TreeView1->Handle,GWL_STYLE,
GetWindowLong(TreeView1->Handle,GWL_STYLE) TVS_CHECKBOXES);
}
//判断一个节点是否处于Checked状态
bool GetNodeChecked(TTreeNode *ANode)
{
TVITEM tvItem;
tvItem.mask = TVIF_HANDLE TVIF_STATE;
tvItem.hItem = ANode->ItemId;
tvItem.stateMask = TVIS_STATEIMAGEMASK;
TreeView_GetItem(ANode->TreeView->Handle, &tvItem);
return ((BOOL)(tvItem.state >> 12) -1);
}
//设置一个节点为Checked状态或者Unchecked状态,由参数IsSetToChecked来确定
void SetNodeChecked(TTreeNode *ANode,bool IsSetToChecked)
{
TVITEM tvItem;
tvItem.mask = TVIF_HANDLE TVIF_STATE;
tvItem.hItem = ANode->ItemId;
tvItem.stateMask = TVIS_STATEIMAGEMASK;
tvItem.state = INDEXTOSTATEIMAGEMASK(IsSetToChecked?2:1);
TreeView_SetItem(ANode->TreeView->Handle, &tvItem);
}
void SetChildChecked(TTreeNode *ANode,bool yn)
{ // 把它的子孙都置成一样
int count=ANode->Count;
SetNodeChecked(ANode,yn);
if (count!=0)
for (int i=0;i<count;i++) // 递归
SetChildChecked(ANode->Item[i],yn);
}
// TTreeNode *ClickNode; // 保存点中的节点
// bool NodeChecked; // 保存点中的节点checked
void __fastcall TForm1::TreeView1MouseMove(TObject *Sender,
TShiftState Shift, int X, int Y)
{
ClickNode=TreeView1->GetNodeAt(X,Y);
if (ClickNode!=NULL) // 保存原节点的Checked值
NodeChecked=GetNodeChecked(ClickNode);
}
void __fastcall TForm1::TreeView1MouseDown(TObject *Sender,
TMouseButton Button, TShiftState Shift, int X, int Y)
{
if (ClickNode!=NULL)
if (GetNodeChecked(ClickNode)!=NodeChecked)
{ // 把它的子孙都置成一样
NodeChecked=!NodeChecked; // 更新它
SetChildChecked(ClickNode,NodeChecked);
}
}