在Delphi中接受文件拖放

用Delphi封装在Form里的那些东西是没办法接受用户从我的电脑里拖放到你的Form上的文件的,但在做软件的时候这又是很必要的,我昨天研究了一晚上终于解决了这个问题。
首先,给你的Project加一个Unit,代码如下:
unit untDrag;

interface

//用来告诉Windows你的Form可以接受文件拖放
{$EXTERNALSYM DragAcceptFiles}procedure DragAcceptFiles(hWnd: Cardinal; fAccept: Boolean); stdcall;
//得到拖放文件名和文件个数的API
{$EXTERNALSYM DragQueryFile}
function DragQueryFile(hDrop: Cardinal; iFile: Cardinal; lpszFile: PChar; cch: Integer): Integer; stdcall;

//释放Windows分配给拖放操作的内存
{$EXTERNALSYM DragFinish}
procedure DragFinish(hDrop: Cardinal); stdcall;
//得到拖放的文件个数
function GetDragFileCount(hDrop: Cardinal): Integer;
//得到拖放的文件名,通过FileIndex来指定文件编号,默认为第一个文件
function GetDragFileName(hDrop: Cardinal; FileIndex: Integer = 1): string;

implementation

procedure DragAcceptFiles; external ??Shell32??;
function DragQueryFile; external ??Shell32??;
procedure DragFinish; external ??Shell32??;

function GetDragFileCount(hDrop: Cardinal): Integer;
const
DragFileCount=High(Cardinal);
begin
Result:= DragQueryFile(hDrop, DragFileCount, nil, 0);
end;

function GetDragFileName(hDrop: Cardinal; FileIndex: Integer = 1): string;
const
Size=255;
var
Len: Integer;
FileName: string;
begin
SetLength (FileName, Size);
Len:= DragQueryFile(hDrop, FileIndex-1, PChar(FileName), Size);
SetLength (FileName, Len);
Result:= FileName;
end;

end.

然后,在你需要处理拖放的Form的OnCreate里面加上这么一句:
DragAcceptFiles (Handle, True);

在TForm1的public里面加上如下声明:
procedure MyDrag (var Msg: TWMDropFiles); message WM_DropFiles;

下面是此过程的实现:
procedure TForm1.MyDrag (var Msg: TWMDropFiles);
var
hDrop: Cardinal;
...
begin
hDrop:= Msg.Drop; //这个是拖放句柄
...(在这里可以用GetDragFileName和GetDragFileCount)
//最后记得要用这两句话:
DragFinish (hDrop);
Msg.Result:= 0;
end;

当然,要在Form的Unit上面加上
uses untDrag;

本文转自
http://topic.csdn.net/u/20080121/01/1d2f3ac0-2e59-47e7-9735-2005336556be.html
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值