如何允许在Delphi中为特定控件拖动文件



我想接受文件,只要有人把文件放到一个特定的控件(例如TMemo)。我从这个例子开始:http://delphi.about.com/od/windowsshellapi/a/accept-filedrop.htm并像这样修改它:

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

这允许控件显示拖拽图标,但适当的WM_DROPFILES消息没有被调用,因为DragAcceptFiles需要一个(父?)窗口句柄。我可以在WMDROPFILES过程中确定MemoHandle,但我不知道如何,加上拖动光标现在适用于所有控件。如何允许对特定控件进行拖动(并阻止其他控件拖动)?

您确实应该传递memo控件的窗口句柄,但随后您还需要收听发送给WM_DROPFILES消息:

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.

上面的例子只接受单个文件的删除。文件名将放在备忘录控件中。但是你也可以允许取消多个选择:

varc:整数;fn: array [0 . .MAX_PATH-1];我:整数;开始

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;

最新更新