本例效果图:


unit Unit1;

interface

uses
  Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
  Dialogs, ComCtrls, StdCtrls;

type
  TForm1 = class(TForm)
    TreeView1: TTreeView;
    procedure FormCreate(Sender: TObject);
    procedure TreeView1DragOver(Sender, Source: TObject; X, Y: Integer;
      State: TDragState; var Accept: Boolean);
    procedure TreeView1DragDrop(Sender, Source: TObject; X, Y: Integer);
  end;

var
  Form1: TForm1;

implementation

{$R *.dfm}

procedure TForm1.FormCreate(Sender: TObject);
var
  stream: TStream;
begin
  TreeView1.Align := alLeft;
  stream := TMemoryStream.Create;
  with TStringList.Create do begin
    Add('一连长');
    Add(' 一排长');
    Add('  一班长');
    Add('   战士1');
    Add('   战士2');
    Add('   战士3');
    Add('   战士4');
    Add('  二班长');
    Add('  三班长');
    Add(' 二排长');
    Add(' 三排长');
    Add('二连长');
    Add('三连长');
    SaveToStream(stream);
    Free;
  end;
  stream.Position := 0;
  TreeView1.LoadFromStream(stream);
  stream.Free;
  TreeView1.DragMode := dmAutomatic; {允许自动拖放}
end;

{只允许拖动子节点}
procedure TForm1.TreeView1DragOver(Sender, Source: TObject; X, Y: Integer;
  State: TDragState; var Accept: Boolean);
begin
  Accept := not TTreeView(Source).Selected.HasChildren;
end;

procedure TForm1.TreeView1DragDrop(Sender, Source: TObject; X, Y: Integer);
var
  n1,n2: TTreeNode;
begin
  if Sender=Source then
  begin
    n1 := TTreeView(Sender).Selected;    {源}
    n2 := TTreeView(Sender).DropTarget;  {目标}
    TreeView1.Items.Insert(n2, n1.Text); {目标前插入}
    n1.Delete;                           {删除源}
  end;
end;

end.

posted on 2008-03-13 17:16  万一  阅读(4554)  评论(9编辑  收藏  举报