递归法选取树子节点 + 控件拖放

类别:Delphi 点击:0 评论:0 推荐:

递归法选取树子节点 + 控件拖放

适合N层树,通用

unit treeRecursion;
{
 标题: 递归法选取树子节点 + 控件拖放
 作者: vigor
 时间: 2004.3.26
}
interface

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

type
  TForm1 = class(TForm)
    TreeView1: TTreeView;
    ListBox1: TListBox;
    Splitter1: TSplitter;
    procedure TreeView1MouseDown(Sender: TObject; Button: TMouseButton;
      Shift: TShiftState; X, Y: Integer);
    procedure ListBox1DragOver(Sender, Source: TObject; X, Y: Integer;
      State: TDragState; var Accept: Boolean);
    procedure ListBox1DragDrop(Sender, Source: TObject; X, Y: Integer);
  private
    { Private declarations }
  public
    { Public declarations }
    procedure AddSelectedChildrenToListbox(tree : TTreeView;startNode :TTreeNode;listBox :TListBox);
  end;

var
  Form1: TForm1;
  g_startNode : TTreeNode;

implementation

{$R *.dfm}
{
拖放控件
准备条件:
      源控件    DragKind :=dkDrag; DragCursor :=crDefalt; DragMode :=  dmManual;
      目标控件
实施步骤:
      1. 开始拖动操作 onMouseDown BeginDrag  ( 源控件 )
    2. 接收拖动项目 OnDragOver             (目标控件)
    3. 放下拖动项目 OnDragDrop             (目标控件)
    4. 终止拖动操作 OnEndDrag             ( 源控件 )
}

procedure TForm1.AddSelectedChildrenToListbox(tree: TTreeView;
                      startNode: TTreeNode; listBox: TListBox);
var
   curParent : TTreeNode;
begin
   if not(tree.Selected.HasChildren) then
   begin
      if listBox.Items.IndexOf(Trim(tree.Selected.Text)) = -1 then
         listBox.Items.Add(Trim(tree.Selected.Text));
   end
   else
   begin
      tree.Selected := tree.Selected.GetNext;
      while tree.Selected<>nil do
      begin
         curParent := tree.Selected;//保护现场^^
         AddSelectedChildrenToListbox(tree,tree.Selected,listBox);
         tree.Selected := curParent.getNextSibling;//恢复现场^^
      end;
   end;
end;

procedure TForm1.TreeView1MouseDown(Sender: TObject; Button: TMouseButton;
  Shift: TShiftState; X, Y: Integer);
begin
   if Button = mbLeft then
   begin
      g_startNode := TreeView1.GetNodeAt(X,Y);
      if Assigned(g_startNode) then
         TreeView1.BeginDrag(True);
   end;
end;

procedure TForm1.ListBox1DragOver(Sender, Source: TObject; X, Y: Integer;
  State: TDragState; var Accept: Boolean);
begin
   if Source = TreeView1 then
      Accept := True;
end;
procedure TForm1.ListBox1DragDrop(Sender, Source: TObject; X, Y: Integer);
begin
   if Source = TreeView1 then
   begin
      AddSelectedChildrenToListbox(treeview1,g_startNode,listbox1);
   end;
end;

end.

本文地址:http://com.8s8s.com/it/it4233.htm