2009. június 8., hétfő

Drag items from a TTreeView onto a TListBox


Problem/Question/Abstract:

I have a treeview which I need to be able to drag items from onto a listbox (they have to be deleted from the treeview when moved, of course). I have been able to do this between two listboxes, but this one eludes me. Can anyone get me started please?

Answer:

procedure TForm1.TreeView1MouseDown(Sender: TObject; Button:
  TMouseButton; Shift: TShiftState; X, Y: Integer);
begin
  if TreeView1.Items.Count = 0 then
    exit;
  if Button = mbLeft then
    TreeView1.BeginDrag(False); {begin drag}
end;

procedure TForm1.ListBox1DragOver(Sender, Source: TObject; X, Y:
  Integer; State: TDragState; var Accept: Boolean);
begin
  Accept := (Sender = TreeView1);
end;

procedure TForm1.ListBox1DragDrop(Sender, Source: TObject; X, Y: Integer);
var
  dx: integer;
  Node: TTreeNode;
begin
  if Source = TreeView1 then
  begin
    Node := TreeView1.Selected;
    if Node <> nil then
    begin
      with TListBox(Sender) do
      begin
        dx := ItemAtPos(Point(X, Y), false);
        Items.Insert(dx, Node.Text);
        {or use:
        Items.InsertObject(dx, Node.Text, Pointer(Node.Data)); }
      end;
      Node.Delete;
    end;
  end;
end;

Nincsenek megjegyzések:

Megjegyzés küldése