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:
- Have a Delphi form named "dropForm".
- Have a Memo control on it, named "memo1".
-
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;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, StdCtrls;
type
TDropForm = class(TForm)
Memo1: TMemo;
procedure FormCreate(Sender: TObject) ;
private
procedure WMDROPFILES(var msg : TWMDropFiles) ; message WM_DROPFILES;
public
{ Public declarations }
end;
var
DropForm: TDropForm;
implementation
{$R *.dfm}
uses ShellApi;
//form's OnCreate event handler
procedure TDropForm.FormCreate(Sender: TObject) ;
begin
//form is ready to accept files
DragAcceptFiles( Handle, True ) ;
end;
(* handle files being dropped on a form *)
procedure TDropForm.WMDROPFILES(var msg: TWMDropFiles) ;
const
MAXFILENAME = 255;
var
cnt, fileCount : integer;
fileName : array [0..MAXFILENAME] of char;
begin
// how many files dropped?
fileCount := DragQueryFile(msg.Drop, $FFFFFFFF, fileName, MAXFILENAME) ;
// query for file names
for cnt := 0 to -1 + fileCount do
begin
DragQueryFile(msg.Drop, cnt, fileName, MAXFILENAME) ;
//do something with the file(s)
memo1.Lines.Insert(0, fileName) ;
end;
//release memory
DragFinish(msg.Drop) ;
end;
end.

