Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I allow dragging files for specific control(s) in Delphi

I would like to accept files as soon as someone drops a file to a specific control (e.g. TMemo). I started with this example: http://delphi.about.com/od/windowsshellapi/a/accept-filedrop.htm and modified it like this:

procedure TForm1.FormCreate(Sender: TObject);
begin
  DragAcceptFiles( Memo1.Handle, True ) ;
end;

This allows the control to show the dragging icon but the proper WM_DROPFILES message is not getting called because DragAcceptFiles needs a (Parent?)windowhandle. I could determine the MemoHandle in the WMDROPFILES procedure but I don't how, plus the dragging cursor applies for all the controls now. How do I allow dragging for a specific control (and block other controls from dragging)?

like image 968
Ben Avatar asked May 20 '13 12:05

Ben


1 Answers

You should indeed pass the window handle of the memo control, but then you also need to listen to the WM_DROPFILES message sent to it:

unit Unit5;

interface

uses
  Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
  Dialogs, StdCtrls, ShellAPI;

type
  TMemo = class(StdCtrls.TMemo)
  protected
    procedure WMDropFiles(var Message: TWMDropFiles); message WM_DROPFILES;
    procedure CreateWnd; override;
    procedure DestroyWnd; override;
  end;

  TForm5 = class(TForm)
    Memo1: TMemo;
    procedure FormCreate(Sender: TObject);
  private
    { Private declarations }
  public
    { Public declarations }
  end;

var
  Form5: TForm5;

implementation

{$R *.dfm}

procedure TForm5.FormCreate(Sender: TObject);
begin
end;

{ TMemo }

procedure TMemo.CreateWnd;
begin
  inherited;
  DragAcceptFiles(Handle, true);
end;

procedure TMemo.DestroyWnd;
begin
  DragAcceptFiles(Handle, false);
  inherited;
end;

procedure TMemo.WMDropFiles(var Message: TWMDropFiles);
var
  c: integer;
  fn: array[0..MAX_PATH-1] of char;
begin

  c := DragQueryFile(Message.Drop, $FFFFFFFF, fn, MAX_PATH);

  if c <> 1 then
  begin
    MessageBox(Handle, 'Too many files.', 'Drag and drop error', MB_ICONERROR);
    Exit;
  end;

  if DragQueryFile(Message.Drop, 0, fn, MAX_PATH) = 0 then Exit;

  Text := fn;

end;


end.

The example above only accept a single file dropped. The file name will be put in the memo control. But you can also allow a multiple selection to be dropped:

var c: integer; fn: array[0..MAX_PATH-1] of char; i: Integer; begin

c := DragQueryFile(Message.Drop, $FFFFFFFF, fn, MAX_PATH);

Clear;
for i := 0 to c - 1 do
begin
  if DragQueryFile(Message.Drop, i, fn, MAX_PATH) = 0 then Exit;
  Lines.Add(fn);
end;
like image 139
Andreas Rejbrand Avatar answered Nov 15 '22 01:11

Andreas Rejbrand