Mega Code Archive

 
Categories / Delphi / Examples
 

Drag and drop files into delphi

This code demonstrates how to drag files from Windows into a Delphi-application. The source application could be anything with drag&drop functionality: Explorer, OutLook, WinZip... unit Unit1; interface uses Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs, StdCtrls; type TForm1 = class(TForm) Memo1: TMemo; procedure FormCreate(Sender: TObject); private // The drop action is trapped by looking for WM_DropFiles messages procedure FileIsDropped(var Msg: TMessage); message WM_DropFiles; { Private declarations } public { Public declarations } end; var Form1: TForm1; implementation uses ShellAPI; {$R *.DFM} procedure TForm1.FormCreate(Sender: TObject); begin // Tell Windows that this form accept dragged files DragAcceptFiles(Handle, true); end; procedure TForm1.FileIsDropped(var Msg: TMessage); var Drop: THandle; FileName: array[0..254] of Char; NumberOfFiles: integer; FileCounter: integer; begin Drop:= Msg.WParam; // If the indexno is 4294967295, the number of dragged items will be retrieved // with DragQueryFile command. // ( The API-manual tells me that the indexno should be -1, which is not a // possible Cardinal-value. 4294967295 is the maximum Cardinal-value, and it // seems to work fine!? Could anybody give me a hint about this? ) NumberOfFiles:= DragQueryFile(Drop, 4294967295, FileName, 254); for FileCounter:= 0 to NumberOfFiles - 1 do begin // Copy the filename,-s with the corresponding value to the buffer FileName. DragQueryFile(Drop, FileCounter, FileName, 254); // Write the filename (without path) to Memo. Memo1.Lines.Add(ExtractFileName(FileName)); end; // Release memory that Windows allocated for use in transferring filenames to // the application. DragFinish(Drop); end; end.