| |
|
Question: How to I accept files dragged from a Windows Explorer window?
Answer: Your Delphi application needs to do the following:
Register itself as a valid drop target.
Support and respond to the WM_DROPFILES message.
When handling WM_DROPFILES, obtain the names of the files dropped from Explorer.
Release the memory Windows allocated to drop the filenames.
The following walkthrough demonstrates each step in turn. In it, you'll create a simple utility that lists the names of files dropped from Explorer.
Create a new Delphi application and then save it to a new directory.
Place a TMemo component on your form.
Add ShellAPI to the form's Uses block.
Add the following code to your form's OnCreate() event:
procedure TForm1.FormCreate(Sender: TObject);
begin
dragAcceptFiles( Handle, True );
end;
This tells Windows your form accepts files dropped from Explorer.
Declare a message handler for the WM_DROPFILES message by adding a declaration to your form's Private section, as shown in the following code:
type
TForm1 = class(TForm)
Memo1: TMemo;
procedure FormCreate(Sender: TObject);
private
{ Private declarations }
procedure OnDroppedFiles( var Msg: TMessage ); message WM_DROPFILES;
public
{ Public declarations }
end;
In the implementation section, create your OnDroppedFiles procedure and add the following code:
procedure TForm1.OnDroppedFiles(var Msg: TMessage);
const
MAXCHARS = 254;
var
hDroppedFile : tHandle;
bFilename : Array[ 0..MAXCHARS ] of char;
intNFiles : integer;
intCounter : integer;
strFilename : String;
begin
strFilename := '';
hDroppedFile := Msg.wParam;
// Get the number of dropped files.
intNFiles := dragQueryFile( hDroppedFile, uint(-1),
bFilename, MAXCHARS );
with Memo1 do
begin
Lines.clear;
for intCounter := ( intNFiles - 1 ) downto 0 do
begin
// Grab the name of a dropped file.
dragQueryFile( hDroppedFile, intCounter,
bFilename, MAXCHARS );
Lines.add( bFilename );
end; // for
end; // with
// Release memory.
dragFinish( hDroppedFile );
end;
Note: This code uses a reverse loop to accept the file names because Windows (generally) presents dropped files in reverse order. The last file selected by the user is typically dropped first while the first selected file is dropped last. This can be unpredictable. You may wish to sort the filenames after accepting them.
Check your sytax and then run your form.
To test your utility, open Windows Explorer, select one or more files, and then drag them to your form. Notice that the memo displays the complete name of the selected files.
|
|