Since I use Drag and Drop support for my applications frequently, and always have to go look back into old code "how I did it before", I decided to post the steps and code that I have created in the past - just so I can find it easier, or maybe because it could help one of the readers here ...
What this will do: You can drop files and directories on the form of your application, and Mac users can additionally drop files on the Dock icon.
Step 1 - Define a constant listing the allowed file extensions, for example:
It's listed this way, so you can use it right away for Open- and SaveDialogs Filters as well, for example:
const allowedExtensions = '*.mp3;*.m4a;*.mp4;*.m4r';
Step 2 - Enable Drag and Drop for your Form
Set "AllowDropFiles" of your TForm to TRUE in the object inspector.
Step 3 - Add an "OnDropFiles" event to your Form
procedure TForm1.FormDropFiles(Sender: TObject; const FileNames: array of String);
var RowCounter,Counter:integer;
begin
for Counter:=0 to Length(FileNames)-1 do
begin
if DirectoryExists(FileNames[Counter]) then
GetFilesInDirs(FileNames[Counter])
else
AddFile(FileNames[Counter]);
end;
end;
Step 4 - Add a function to parse through directories
Since we'd like to accept both files and directories, we need to make sure we go through the files in received directories and it's potential sub-directories.
procedure TForm1.GetFilesInDirs(Dir:string);
var DirInfo:TSearchRec;
begin
if FindFirst(Dir+DirectorySeparator+'*', faAnyFile and faDirectory, DirInfo)=0 then
repeat
if (DirInfo.Attr and faDirectory) = faDirectory then // it's a dir - go get files in dir
begin
if (DirInfo.Name<>'.') and (DirInfo.Name<>'..') then
GetFilesInDirs(Dir+DirectorySeparator+DirInfo.Name);
end
else // It's a file; add it
AddFile(Dir+DirectorySeparator+DirInfo.Name);
until FindNext(DirInfo)<>0;
FindClose(DirInfo);
end;
Step 5 - Add a function to add files to something like a list
I've quickly added a TMemo to the form, just as an example.
procedure TForm1.AddFile(Filename:string);
begin
if (FileName<>'') and (Pos(LowerCase(ExtractFileExt(Filename)), allowedExtensions)>0) then
begin
Memo1.lines.add(Filename); // write your own code here, this is just an example
end;
end;
And you're done ...