How to Receive Drag-and-Drop Files in Delphi VCL — WM_DROPFILES and DragQueryFile Implementation Examples
In Delphi VCL, you can obtain file paths by dragging and dropping files or folders from Windows Explorer onto a form or control.
This page explains in detail how to handle drop operations using the Windows API WM_DROPFILES message together with the ApplicationEvents component.
It includes practical sample code demonstrating how to retrieve file names with DragQueryFile and DragQueryPoint, display dropped items in a ListBox, and output logs to a Memo.
If you want to implement drag‑and‑drop functionality in your Delphi applications, this guide will be a helpful reference.
Creating the Project and Form
Start the Delphi IDE and select "File" -> "Windows VCL Application – Delphi".
Drag and drop the following components onto the form:
one TListBox, one TMemo, and one TApplicationEvents.
Writing the Source Code
unit Unit1;
interface
uses
Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes,
Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.AppEvnts, Vcl.StdCtrls;
type
TForm1 = class(TForm)
ListBox1: TListBox;
Memo1: TMemo;
ApplicationEvents1: TApplicationEvents;
procedure ApplicationEvents1Message(var Msg: tagMSG; var Handled: Boolean);
procedure FormCreate(Sender: TObject);
private
{ Private declarations }
public
{ Public declarations }
end;
var
Form1: TForm1;
implementation
{$R *.dfm}
uses Winapi.ShellAPI;
procedure TForm1.ApplicationEvents1Message(var Msg: tagMSG;
var Handled: Boolean);
var DropCount:Cardinal;
i:Cardinal;
FileName:array[0..4096] of Char;
p:TPoint;
begin
Handled:=False;
if Msg.message=WM_DROPFILES then
begin
//Get the drop coordinates (relative to the form or control)
DragQueryPoint(Msg.wParam,p);
Memo1.Lines.Add('座標:'+Format('%d,%d',[p.X,p.Y]));
//Identify which control received the drop
if Msg.hwnd=Form1.Handle then
Memo1.Lines.Add('Dropped on Form1')
else if Msg.hwnd=ListBox1.Handle then
Memo1.Lines.Add('Dropped on ListBox1')
else if Msg.hwnd=Memo1.Handle then
Memo1.Lines.Add('Dropped on Memo1');
try
//Get the number of dropped files/folders
DropCount := DragQueryFile(Msg.wParam, Cardinal(-1), nil, 0);
for i := 0 to DropCount-1 do
begin
DragQueryFile(Msg.wParam, i, FileName, Length(FileName));
//Display the dropped file/folder in ListBox1
ListBox1.Items.Add(FileName);
end;
finally
DragFinish(Msg.wParam);
end;
end;
end;
procedure TForm1.FormCreate(Sender: TObject);
begin
//Enable file drop on Form1
DragAcceptFiles(Self.Handle, True);
//Enable file drop on ListBox1
DragAcceptFiles(ListBox1.Handle, True);
//Enable file drop on Memo1
DragAcceptFiles(Memo1.Handle, True);
end;
end.
Running the Application
When you drag and drop files or folders onto the form window, or onto Memo1 or ListBox1, the dropped items will be listed in ListBox1.
