Drag & Drop Files in Delphi

uses ShellAPI

procedure TForm1.FormCreate(Sender: TObject);
begin
 // ... other code here
 DragAcceptFiles(Self.Handle, True);
 // ... other code here
end;



procedure TForm1.WMDropFiles(var Msg: TWMDropFiles);
var
 DropH: HDROP; // drop handle
 DroppedFileCount: Integer; // number of files dropped
 FileNameLength: Integer; // length of a dropped file name
 FileName: string; // a dropped file name
 I: Integer; // loops thru all dropped files
 DropPoint: TPoint; // point where files dropped
begin
 inherited;
 // Store drop handle from the message
 DropH := Msg.Drop;
 try
 // Get count of files dropped
 DroppedFileCount := DragQueryFile(DropH, $FFFFFFFF, nil, 0);
 // Get name of each file dropped and process it
 for I := 0 to Pred(DroppedFileCount) do
 begin
 // get length of file name
 FileNameLength := DragQueryFile(DropH, I, nil, 0);
 // create string large enough to store file
 // (Delphi allows for #0 terminating character automatically)
 SetLength(FileName, FileNameLength);
 // get the file name
 DragQueryFile(DropH, I, PChar(FileName), FileNameLength + 1);
 // process file name (application specific)
 // ... processing code here
 end;
 // Optional: Get point at which files were dropped
 DragQueryPoint(DropH, DropPoint);
 // ... do something with drop point here
 finally
 // Tidy up - release the drop handle
 // don't use DropH again after this
 DragFinish(DropH);
 end;
 // Note we handled message
 Msg.Result := 0;
end;


procedure TForm1.FormDestroy(Sender: TObject);
begin
 // ... other code here
 DragAcceptFiles(Self.Handle, False);
 // ... other code here
end;

 

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s