How to copy filenames to the clipboard with Delphi

////////////////////////////////////////////////////////////////
  // copies filenames from "Filenames" to the clipboard.
  // "Filenames" can contain file- and directory names.

function Sto_CopyFilenamesToClipboard(Filenames: TStrings): Boolean;
var
  sFilenames: string;
  iIndex: Integer;
  hBuffer: HGLOBAL;
  pBuffer: PDropFiles;
begin// check entry conditions
  Result := (Filenames <> nil) and (Filenames.Count > 0);
  if (not Result) then
    Exit;// bring the filenames in a form,
         // separated by #0 and ending with a double #0#0
  sFilenames := '';
  for iIndex := 0 to Filenames.Count - 1 do
    sFilenames := sFilenames + ExcludeTrailingPathDelimiter(Filenames.Strings[iIndex])
      + #0;
  sFilenames :=
    sFilenames + #0;
  // allocate memory with the size of the "DropFiles" structure plus the
  // length of the filename buffer.
  hBuffer := GlobalAlloc(GMEM_MOVEABLE or GMEM_ZEROINIT,
    SizeOf(DROPFILES) + Length(sFilenames));
  try
    Result := (hBuffer <> 0);
    if (Result) then
    begin
      pBuffer := GlobalLock(hBuffer);
      try// prepare the "DROPFILES" structure
        pBuffer^.pFiles := SizeOf(DROPFILES);
        // behind the "DROPFILES" structure we place the filenames
        pBuffer := Pointer(Integer(pBuffer) + SizeOf(DROPFILES));
        CopyMemory(pBuffer, PChar(sFilenames), Length(sFilenames));
      finally
        GlobalUnlock(hBuffer);
      end;// copy buffer to the clipboard
      Clipboard.Open;
      try
        Clipboard.SetAsHandle(CF_HDROP, hBuffer);
      finally
        Clipboard.Close;
      end;
    end;
  except
    Result := false;// free only if handle could not be passed to the clipboard
    GlobalFree(hBuffer);
  end;
end;

No comments:

Post a Comment