Handling Drag-and-Drop Files in Delphi FMX — Implementing WM_DROPFILES and DragQueryFile
In Delphi FMX, you can obtain file paths by dragging and dropping files onto a form or control using the Windows API.
This page explains in detail how to replace the Window Procedure to receive the WM_DROPFILES message and how to retrieve file names using the DragQueryFile function.
It also includes practical sample code for displaying dropped items in a ListBox and enabling drop acceptance with DragAcceptFiles.
If you want to implement file drag‑and‑drop functionality in a Delphi FMX application, this guide will be a helpful reference.
Creating the Project and Form
Start the Delphi IDE and select "File" -> "New" -> "Multi‑Device Application – Delphi".
Choose "Blank Application" and click the "OK" button.
Drag and drop one TListBox onto the form.
Writing the Source Code
unit Unit1; interface uses System.SysUtils, System.Types, System.UITypes, System.Classes, System.Variants, FMX.Types, FMX.Controls, FMX.Forms, FMX.Graphics, FMX.Dialogs, FMX.Layouts, FMX.ListBox, FMX.Platform.Win, //Defines FormToHWND winapi.Windows, //Defines HWND and related types Winapi.ShellAPI, //Defines DragAcceptFiles Winapi.Messages; //Defines WM_DROPFILES and related messages type TForm1 = class(TForm) ListBox1: TListBox; procedure FormCreate(Sender: TObject); private { private 宣言 } public { public 宣言 } end; //Window Procedure to replace the original one function NewWndProc(hwnd:HWND;uMsg:UINT;wParam:WPARAM;lParam:LPARAM):LRESULT;stdcall; var Form1: TForm1; OldWndProc:NativeInt; //Stores the original Window Procedure wHandle:HWND; //Stores this form's window handle implementation {$R *.fmx} //Replacement Window Procedure function NewWndProc(hwnd: HWND; uMsg: UINT; wParam: WPARAM; lParam: LPARAM): LRESULT; var DropCount:Cardinal; i:Integer; FileName:array[0..4096] of Char; begin //When files or folders are dropped onto Form1 if uMsg=WM_DROPFILES then begin try //Get the number of dropped files/folders DropCount := DragQueryFile(wParam, Cardinal(-1), nil, 0); for i := 0 to DropCount-1 do begin DragQueryFile(wParam, i, FileName, Length(FileName)); //Display the dropped file/folder in ListBox1 Form1.ListBox1.Items.Add(FileName); end; finally DragFinish(wParam); end; end; //Call the original Window Procedure Result:=CallWindowProc(Pointer(oldWndProc),WHandle,uMsg,wParam,LParam); end; procedure TForm1.FormCreate(Sender: TObject); begin //Retrieve this form's window handle wHandle := FormToHWND(self); //Alternatively //wHandle := WindowHandleToPlatform(self.Handle).Wnd; //Replace the Window Procedure oldWndProc:=SetWindowLong(WHandle,GWL_WNDPROC,NativeInt(@NewWndProc)); //Enable file drop on Form1 DragAcceptFiles(wHandle, True); end; end.
Running the Application
When you drag and drop files or folders onto the form window, the dropped items will appear in ListBox1.
