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);
}
}