1. Technology

Allow your Delphi Forms to Accept Dropped Files from Window Explorer

Handle Files Being Dropped on your Form


Drag and drop operations are commonly used operations in Windows applications. When working with Window Explorer you can copy, move and even delete files by using drag and drop.

Moving an object with the mouse button pressed is usually called dragging, and what happens when we end dragging by releasing the mouse button is called dropping.

While drag and drop is implemented in the VCL, to accept files from dragged from the Windows Explorer you need to handle a few shell api messages.

I can accept files!

For an object (window), like a Delphi form, to be able to accept files from the Windows shell a call to DragAcceptFiles is required. Next, a handler for the WM_DROPFILES message needs to be provided.

Here's an example:

  1. Have a Delphi form named "dropForm".
  2. Have a Memo control on it, named "memo1".
    1. The code registers a form as a window that accepts dropped files in the form's OnCreate event. The WMDROPFILES procedure handles files being dropped by listing their names in the memo control.
       unit dropFormUnit;
         Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
         Dialogs, StdCtrls;
         TDropForm = class(TForm)
           Memo1: TMemo;
           procedure FormCreate(Sender: TObject) ;
           procedure WMDROPFILES(var msg : TWMDropFiles) ; message WM_DROPFILES;
           { Public declarations }
         DropForm: TDropForm;
       {$R *.dfm}
       uses ShellApi;
       //form's OnCreate event handler
       procedure TDropForm.FormCreate(Sender: TObject) ;
         //form is ready to accept files
         DragAcceptFiles( Handle, True ) ;
       (* handle files being dropped on a form *)
       procedure TDropForm.WMDROPFILES(var msg: TWMDropFiles) ;
         MAXFILENAME = 255;
         cnt, fileCount : integer;
         fileName : array [0..MAXFILENAME] of char;
         // how many files dropped?
         fileCount := DragQueryFile(msg.Drop, $FFFFFFFF, fileName, MAXFILENAME) ;
         // query for file names
         for cnt := 0 to -1 + fileCount do
           DragQueryFile(msg.Drop, cnt, fileName, MAXFILENAME) ;
           //do something with the file(s)
           memo1.Lines.Insert(0, fileName) ;
         //release memory
         DragFinish(msg.Drop) ;

©2014 About.com. All rights reserved.