Delphi TreeView树型框节点拖拽停靠、按条件开始拖拽时间:2022-02-24 12:56:07OnDragOver处理是否允许放下 procedure TMainForm.TreeViewDragOver(Sender, Source: TObject; X, Y: Integer; State: TDragState; var Accept: Boolean); var TargetNode, SourceNode: TTreeNode; begin Accept := False; TargetNode := TTreeView(Sender).GetNodeAt(X, Y); if (Source = Sender) and (TargetNode <> nil) then begin Accept := True; SourceNode := TTreeView(Sender).Selected; if TargetNode = SourceNode.Parent then Accept := False; if Accept then begin while (TargetNode.Parent <> nil) and (TargetNode <> SourceNode) do TargetNode := TargetNode.Parent; if TargetNode = SourceNode then Accept := False; end; end; end; OnDragDrop是放下后节点的处理方法 procedure TMainForm.TreeViewDragDrop(Sender, Source: TObject; X, Y: Integer); var TargetNode, SourceNode: TTreeNode; begin TargetNode := TTreeView(Sender).GetNodeAt(X, Y); if TargetNode <> nil then begin SourceNode := TTreeView(Sender).Selected; TTreeView(Sender).Items.BeginUpdate; SourceNode.MoveTo(TargetNode, naAddChildFirst); TTreeView(Sender).Selected := SourceNode; TTreeView(Sender).Items.EndUpdate; end; end; 另外TreeView本身还需要设定支持拖放,俩个方法 1: 静态设定TreeView可以拖放 procedure TMainForm.FormCreate(Sender: TObject); begin TreeView.DragMode := dmAutomatic; // end; 2: 通过事件动态设定 procedure TMainForm.TreeViewMouseDown(Sender: TObject; Button: TMouseButton; Shift: TShiftState; X, Y: Integer); begin if (Button = mbLeft) and (htOnItem in TTreeView(Sender).GetHitTestInfoAt(X, Y)) then //判断是左键并且点击在Item上 begin if (ssCtrl in Shift) then //如果按下了Ctrl键 TTreeView(Sender).BeginDrag(False); //允许拖放 end; end;