Accept files dragged over an application (Views: 14859)


If you have an application that works with files, you probably want that users would be able to drag and drop files over your application to open them.


For your application be able to accept files when dropped over it, you need to tell windows that your application can accept files. To do this, you have two options:

Make use of Params.ExStyle
To be able to accept files without much trouble you have just to override the protected the protected procedure CreateParams and write the following:

procedure TForm1.CreateParams(var Params: TCreateParams);
  inherited CreateParams(Params);
  // Register the window to be able to accept dropped files
  Params.ExStyle := Params.ExStyle or WS_EX_ACCEPTFILES;

Use API function DragAcceptFiles
The other option is use DragAcceptFiles API function. This way you can control if your application can accept dropped files or not without the need to change Params.ExStyle

Both options of activation activate the WM_DROPFILES windows message, and it's here that you'll have to process the dropped files.

The following routine gives the essential part of what you need to do:

procedure TForm1.WMDropFiles(var Message: TWMDropFiles);
// The WM_DROPFILES message is sent when the user releases the left mouse button
//    while the cursor is in the window of an application that has registered
//    itself as a recipient of dropped files.
  FNumFiles: Integer;
  i: Integer;
  BufSize: Integer;
  FFilePath: array of char;
  FFileName: string;

  // How many files were dropped ?
  FNumFiles := DragQueryFile(Message.Drop, $FFFFFFFF, nil, 0);
  // Process all files in the list
  for i := 0 to FNumFiles - 1 do
    // Get the buffer size to old the filename
    BufSize := DragQueryFile(Message.Drop, i, nil, 0);
    // Get filename. This filename is a null-terminated string.
    SetLength(FFilePath, BufSize + 1);
    DragQueryFile(Message.Drop, i, PChar(FFilePath), BufSize + 1);
    // Check if the dropped file extension can be accepted
    FFileName := ExtractFileName(PChar(FFilePath));

  // The DragFinish function releases memory that Windows allocated for use in
  //    transferring filenames to the application.

Attached is a project sample. It's a small file text viewer and it implement's a bit more than the above, as you can see in the following screen shot.

<< Back to main page