Delphi - 使用ListView拖放

Nan*_*nik 3 delphi listview drag-and-drop file handle

晚上好 :-)!

我有这个代码使用拖放方法的文件:

TForm1 = class(TForm)
...
public
    procedure DropFiles(var msg: TMessage ); message WM_DROPFILES;
end;

procedure TForm1.FormCreate(Sender: TObject)
begin
    DragAcceptFiles(ListView1.Handle, True);
end;
Run Code Online (Sandbox Code Playgroud)
procedure TForm1.DropFiles(var msg: TMessage );
var
  i, count  : integer;
  dropFileName : array [0..511] of Char;
  MAXFILENAME: integer;
begin
  MAXFILENAME := 511;
  count := DragQueryFile(msg.WParam, $FFFFFFFF, dropFileName, MAXFILENAME);
  for i := 0 to count - 1 do
  begin
    DragQueryFile(msg.WParam, i, dropFileName, MAXFILENAME);
    Memo1.Lines.Add(dropFileName);
  end;
  DragFinish(msg.WParam);
end;
Run Code Online (Sandbox Code Playgroud)

ListView区域是DragCursor,但在Memo1 中没有任何记录.当我使用例如ListBox和方法DragAcceptFiles(ListBox1.Handle,True)时,一切都很好.

ListView属性DragMode我设置为dmAutomatic.

谢谢 :-)

And*_*den 7

您已为ListView调用DragAcceptFiles,因此Windows将WM_DROPFILES发送到ListView而不是表单.您必须从ListView捕获WM_DROPFILES消息.

  private
    FOrgListViewWndProc: TWndMethod;
    procedure ListViewWndProc(var Msg: TMessage);
  // ...
  end;

procedure TForm1.FormCreate(Sender: TObject);
begin
  // Redirect the ListView's WindowProc to ListViewWndProc
  FOrgListViewWndProc := ListView1.WindowProc;
  ListView1.WindowProc := ListViewWndProc;

  DragAcceptFiles(ListView1.Handle, True);
end;

procedure TForm1.ListViewWndProc(var Msg: TMessage);
begin
  // Catch the WM_DROPFILES message, and call the original ListView WindowProc 
  // for all other messages.
  case Msg.Msg of
    WM_DROPFILES:
      DropFiles(Msg);
  else
    if Assigned(FOrgListViewWndProc) then
      FOrgListViewWndProc(Msg);
  end;
end;
Run Code Online (Sandbox Code Playgroud)