unit Unit1; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, StdCtrls; type TForm1 = class(TForm) ListBox1: TListBox; ListBox2: TListBox; PRocedure ListBox1DragDrop(Sender, Source: TObject; X, Y: Integer); procedure ListBox1DragOver(Sender, Source: TObject; X, Y: Integer; State: TDragState; var Accept: Boolean); private FDragOverObject: TObject; //ListBox1DragDrop、ListBox1DragOver由多個Listbox共享,這里記錄當前那個Listbox接受鼠標拖放 FDragOverItemIndex: Integer; //記錄鼠標所在條目的Index procedure DrawInsertLine; public { Public declarations } end; var Form1: TForm1; implementation {$R *.dfm}
{======================================================================== DESIGN BY : 彭國輝 DATE: 2004-12-24 SITE: http://kacarton.yeah.net/ BLOG: http://blog.csdn.net/nhconch EMAIL: kacarton#sohu.com 文章為作者原創,轉載前請先與本人聯系,轉載請注明文章出處、保留作者信息,謝謝支持! =========================================================================}
procedure TForm1.ListBox1DragDrop(Sender, Source: TObject; X, Y: Integer); var i: integer; begin //拖放完成,將內容從原來的Listbox讀到目標Listbox with TListBox(Source) do begin i := TListBox(Sender).ItemAtPos(Point(X, Y) , true); if i<>-1 then TListBox(Sender).Items.InsertObject(i, Items[ItemIndex], Items.Objects[ItemIndex]) else i := TListBox(Sender).Items.AddObject(Items[ItemIndex], Items.Objects[ItemIndex]); if (Sender=Source) and (i>ItemIndex) then i := i-1; DeleteSelected; if (Sender=Source) then ItemIndex := i; end; FDragOverObject := nil; FDragOverItemIndex := -1; end; procedure TForm1.ListBox1DragOver(Sender, Source: TObject; X, Y: Integer; State: TDragState; var Accept: Boolean); var Index: Integer; begin Accept := (Source is TListBox) and (TListBox(Source).ItemIndex>-1); //只接受來自Listbox的內容 if not Accept then Exit; if (FDragOverObject<>nil) and (Sender<>FDragOverObject) then DrawInsertLine; //鼠標離開Listbox時,擦除插入位置提示線框 Index := TListBox(Sender).ItemAtPos(Point(X, Y) , true); if (FDragOverObject = Sender) and (FDragOverItemIndex = Index) then Exit; //當鼠標在同一條目上移動時,只畫一次即可 if (FDragOverObject = Sender) and (FDragOverItemIndex <> Index) then DrawInsertLine; //鼠標移到新位置,擦除舊的插入位置提示線框 FDragOverObject := Sender; FDragOverItemIndex := Index; DrawInsertLine; //畫出插入位置提示線框 end; procedure TForm1.DrawInsertLine; var R: TRect; begin if FDragOverObject = nil then Exit; with TListBox(FDragOverObject) do begin if FDragOverItemIndex > -1 then begin R := ItemRect(FDragOverItemIndex); R.Bottom := R.Top + 4; end else if Items.Count>0 then begin R := ItemRect(Items.Count-1); R.Top := R.Bottom - 4; end else begin windows.GetClientRect(Handle, R); R.Bottom := R.Top + 4; end; DrawFocusRect(Canvas.Handle, R); InflateRect(R, -1, -1); DrawFocusRect(Canvas.Handle, R); end; end; end.
|