Delphi 复制文件到剪贴板

将文件复制或剪切到剪贴板,可以在资源管理器、桌面等地方粘贴。在网上找了下,找到一些代码,不过发现都有点bug,现在将修正后的分享出来。

procedure CutOrCopyFiles(FileList: AnsiString; bCopy: Boolean);
type
  PDropFiles = ^TDropFiles;

  TDropFiles = record
    pfiles: DWORD;
    pt: TPoint;
    fNC: BOOL;
    fwide: BOOL;
  end;
const
  DROPEFFECT_COPY = 1;
  DROPEFFECT_MOVE = 2;
var
  hGblFileList: hGlobal;
  pFileListDate: Pbyte;
  HandleDropEffect: UINT;
  hGblDropEffect: hGlobal;
  pdwDropEffect: PDWORD;
  iLen: Integer;
begin
  iLen := Length(FileList) + 2;
  FileList := FileList + #0#0;
  hGblFileList := GlobalAlloc(GMEM_ZEROINIT or GMEM_MOVEABLE or GMEM_SHARE,
    SizeOf(TDropFiles) + iLen);
  pFileListDate := GlobalLock(hGblFileList);
  PDropFiles(pFileListDate)^.pfiles := SizeOf(TDropFiles);
  PDropFiles(pFileListDate)^.pt.Y := 0;
  PDropFiles(pFileListDate)^.pt.X := 0;
  PDropFiles(pFileListDate)^.fNC := False;
  PDropFiles(pFileListDate)^.fwide := False;
  Inc(pFileListDate, SizeOf(TDropFiles)); // Ö¸ÕëºóÒÆ
  CopyMemory(pFileListDate, @FileList[1], iLen);
  GlobalUnlock(hGblFileList);
  HandleDropEffect := RegisterClipboardFormat('Preferred DropEffect ');
  hGblDropEffect := GlobalAlloc(GMEM_ZEROINIT or GMEM_MOVEABLE or GMEM_SHARE,
    SizeOf(DWORD));
  pdwDropEffect := GlobalLock(hGblDropEffect);
  if (bCopy) then pdwDropEffect^ := DROPEFFECT_COPY
  else pdwDropEffect^ := DROPEFFECT_MOVE;
  GlobalUnlock(hGblDropEffect);
  if OpenClipboard(0) then begin
    EmptyClipboard();
    SetClipboardData(HandleDropEffect, hGblDropEffect);
    SetClipboardData(CF_HDROP, hGblFileList);
    CloseClipboard();
  end;
end;

procedure CopyFileClipbrd(const FName: string);
begin
  CutOrCopyFiles(AnsiString(FName), True);
end;

 

 

分享到: