How can I drag & drop a file from the shell?

rsltgy picture rsltgy · Aug 21, 2014 · Viewed 7.4k times · Source

I am trying to drag and drop a video file (like .avi) from desktop But ı can not take it to the my program.But when ı try to drag and drop inside my program it works fine.For ex: I have an edittext and a listbox inside my pro and ı can move text that inside edittext to listbox.I could not get what is the difference ??

I take the video using openDialog.But ı wanna change it with drag and drop.

procedure TForm1.Button1Click(Sender: TObject);
   begin
     if OpenDialog1.Execute then
       begin
          MediaPlayer1.DeviceType:=dtAutoSelect;
          MediaPlayer1.FileName := OpenDialog1.FileName;
          Label1.Caption := ExtractFileExt(MediaPlayer1.FileName);
          MediaPlayer1.Open;
          MediaPlayer1.Display:=Self;
          MediaPlayer1.DisplayRect := Rect(panel1.Left,panel1.Top,panel1.Width,panel1.Height);
          panel1.Visible:=false;
          MediaPlayer1.Play;
       end;

   end;

Answer

kludg picture kludg · Aug 21, 2014

Here is a simple demo how to drag&drop files from Windows Explorer into a ListBox (for Delphi XE):

unit Unit1;

interface

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

type
  TForm1 = class(TForm)
    ListBox1: TListBox;
    procedure FormCreate(Sender: TObject);
    procedure FormDestroy(Sender: TObject);
  private
    { Private declarations }
  protected
    procedure WMDropFiles(var Msg: TMessage); message WM_DROPFILES;
  public
    { Public declarations }
  end;

var
  Form1: TForm1;

implementation

{$R *.dfm}

uses ShellAPI;

procedure TForm1.FormCreate(Sender: TObject);
begin
  DragAcceptFiles(Handle, True);
end;

procedure TForm1.FormDestroy(Sender: TObject);
begin
  DragAcceptFiles(Handle, False);
end;

procedure TForm1.WMDropFiles(var Msg: TMessage);
var
  hDrop: THandle;
  FileCount: Integer;
  NameLen: Integer;
  I: Integer;
  S: string;

begin
  hDrop:= Msg.wParam;
  FileCount:= DragQueryFile (hDrop , $FFFFFFFF, nil, 0);

  for I:= 0 to FileCount - 1 do begin
    NameLen:= DragQueryFile(hDrop, I, nil, 0) + 1;
    SetLength(S, NameLen);
    DragQueryFile(hDrop, I, Pointer(S), NameLen);

    Listbox1.Items.Add (S);
  end;

  DragFinish(hDrop);
end;

end.