How to copy filenames from the clipboard with Delphi


uses Clipbrd, ShellApi, ShlObj, Windows, SysUtils;////////////////////////////////////////////////////////////////
  // copies filenames from the clipboard to "Filenames" if there
  // are any. the clipboard can contain file- and directory names.

procedure Sto_PasteFilenamesFromClipboard(Filenames: TStrings);
var
  hDropHandle: HDROP;
  szBuffer: PChar;
  iCount, iIndex: Integer;
  iLength: Integer;
begin// check entry conditions
  if (Filenames = nil) then
    Exit;
  Filenames.Clear;// lock clipboard
  Clipboard.Open;
  try// does clipboard contain filenames?
    if (Clipboard.HasFormat(CF_HDROP)) then
    begin// get drop handle from the clipboard
      hDropHandle := Clipboard.GetAsHandle(CF_HDROP);// enumerate filenames
      iCount := DragQueryFile(hDropHandle, $FFFFFFFF, nil, 0);
      for iIndex := 0 to iCount - 1 do
      begin// get length of filename
        iLength := DragQueryFile(hDropHandle, iIndex, nil, 0);
        // allocate the memory, the #0 is not included in "iLength"
        szBuffer := StrAlloc(iLength + 1);
        try// get filename
          DragQueryFile(hDropHandle, iIndex, szBuffer, iLength + 1);
          Filenames.Add(szBuffer);
        finally// free the memory
          StrDispose(szBuffer);
        end;
      end;
    end;
  finally// unlock clipboard
    Clipboard.Close;
  end;
end;

No comments:

Post a Comment