都是激发DragOver事件和DragDrop事件

解决方案 »

  1.   

    unit UnitListBoxDrag;
    //用鼠标拖动对LISTBOX中的ITEM直接上移;或下移
    interfaceuses
      Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
      Dialogs, StdCtrls;type
      TForm1 = class(TForm)
        ListBox1: TListBox;     //DragMode:=dmManual
        procedure ListBox1MouseDown(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 }
      end;var
      Form1: TForm1;implementation{$R *.dfm}procedure TForm1.ListBox1MouseDown(Sender: TObject; Button: TMouseButton;
      Shift: TShiftState; X, Y: Integer);
    begin
      if Button = mbLeft then
      with Sender as TListBox do
      begin
        if ItemAtPos(Point(X, Y), True)  >=  0 then //保证ListBox1DragDrop中nS>=0
            BeginDrag(False);  //允许ListBox单独处理鼠标事件而并不开始拖动
      end;
    end;procedure TForm1.ListBox1DragOver(Sender, Source: TObject; X, Y: Integer;
      State: TDragState; var Accept: Boolean);
    begin
         Accept:=false;
         if (Source is TListBox) and  (TListBox(sender).ItemAtPos(Point(X, Y), True)  >= 0) then
        Accept := True;   //保证ListBox1DragDrop中nD>=0
    end;procedure TForm1.ListBox1DragDrop(Sender, Source: TObject; X, Y: Integer);
    var
        sTemp:String;
        nS,nD:integer;
    begin
        nS:=ListBox1.ItemIndex;  //当前列表项索引号(拖放的源地址)
        nD:=ListBox1.ItemAtPos(Point(X, Y), True); //目的索引号
        sTemp:=ListBox1.Items[nS];//储存源项
        ListBox1.Items[nS]:=ListBox1.Items[nD];//交换源,目的项值
        ListBox1.Items[nD]:=sTemp;
    end;
    end.