Mega Code Archive

 
Categories / Delphi / Examples
 

Drag and drop from explorer

This article demonstrates how to accept files dropped from outside of your Delphi application. unit Unit1; interface uses Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs, StdCtrls; type TForm1 = class(TForm) procedure FormCreate(Sender: TObject); procedure FormDestroy(Sender: TObject); private { Private declarations } protected procedure WMDropFiles(var Msg: TWMDropFiles); message WM_DROPFILES; public { Public declarations } end; var Form1: TForm1; implementation {$R *.DFM} uses ShellAPI; procedure TForm1.FormCreate(Sender: TObject); begin { This call to DragAcceptFiles tells Windows that we want to know when files are dropped on our form from Explorer or File Manager. } DragAcceptFiles(Handle, TRUE); end; procedure TForm1.FormDestroy(Sender: TObject); begin { Notify Windows that we no longer want drop notification messages. } DragAcceptFiles(Handle, FALSE); end; procedure TForm1.WMDropFiles(var Msg: TWMDropFiles); var I: integer; S: string; begin with Msg do begin { Calling DragQueryFile with the file number as -1 ($FFFFFFFF) will return the number of files which were dropped on the form. } for I := 0 to DragQueryFile(Drop, -1, nil, 0) - 1 do begin { Here we call DragQueryFile for each file dropped specifying a buffer length of zero the determine the number of characters needed for the filename, and then use SetLength to allocate the proper amount of space. Note that we must add one to the value returned by DragQueryFile to leave room for the null-terminator. } SetLength(S, DragQueryFile(Drop, I, nil, 0)+1); { Get the complete filename in S. Any processing which needs to be done for each file can be done after this call. } DragQueryFile(Drop, I, PChar(S), Length(S)); end; { DragFinish completes the operation and frees the associated resources. } DragFinish(Drop); end; end; end.