Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Drag and Drop files to Delphi form not working

I've tried to accept files that are dragged and dropped to a Form from the File Explorer but it doesn't work. My WM_DROPFILES handler is never called. I'm running Windows 8 if that makes any difference.

Here's a simple example of what I do (I just have a TMemo on the form):

type
  TForm1 = class(TForm)
    Memo1: TMemo;
  private
    { Private declarations }
    procedure WMDROPFILES(var msg : TWMDropFiles) ; message WM_DROPFILES;
    procedure CreateWnd; override;
    procedure DestroyWnd; override;
  public
    { Public declarations }
  end;

var
  Form1: TForm1;

implementation

{$R *.dfm}

{ TForm1 }

procedure TForm1.CreateWnd;
begin
  inherited;
  DragAcceptFiles(Handle, True);

end;

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

end;

procedure TForm1.WMDROPFILES(var msg: TWMDropFiles);
var
  i, fileCount: integer;
  fileName: array[0..MAX_PATH] of char;
begin
  fileCount:=DragQueryFile(msg.Drop, $FFFFFFFF, fileName, MAX_PATH);
  for i := 0 to fileCount - 1 do
  begin
    DragQueryFile(msg.Drop, i, fileName, MAX_PATH);
    Memo1.Lines.Add(fileName);
  end;
  DragFinish(msg.Drop);
end;
like image 326
Joacim Andersson Avatar asked Jan 09 '13 18:01

Joacim Andersson


1 Answers

Most likely you are running your application elevated. Probably because you are running Delphi elevated. In Vista and later, low privilege processes cannot send messages to higher privilege processes. This MSDN blog explains more.

If you are running your Delphi IDE elevated, I urge you to stop doing so. There's very seldom a need to do so for standard desktop application development.


As Remy points out, your DestroyWnd is incorrect. You are destroying the window handle before calling DragAcceptFiles. Simply reverse the order. Personally I'd use WindowHandle in both CreateWnd and DestroyWnd. The Handle property creates the window handle if it is not assigned and so masks such errors.

procedure TForm1.CreateWnd;
begin
  inherited;
  DragAcceptFiles(WindowHandle, True);
end;

procedure TForm1.DestroyWnd;
begin
  DragAcceptFiles(WindowHandle, false);
  inherited;
end;
like image 61
David Heffernan Avatar answered Nov 13 '22 15:11

David Heffernan