6

I would like to retrieve the file size of a file copied into the clipboard.

I read the documentation of TClipboard but I did not find a solution.

I see that TClipboard.GetAsHandle could be of some help but I was not able to complete the task.

pppery
  • 3,731
  • 22
  • 33
  • 46
UnDiUdin
  • 14,924
  • 39
  • 151
  • 249
  • You can read this articles: [article 1](https://learn.microsoft.com/ru-ru/windows/win32/shell/clipboard?redirectedfrom=MSDN) and [article 2](https://learn.microsoft.com/en-us/windows/win32/dataxchg/clipboard). VCL's docs on `TClipboard` not very useful in your case. – Josef Švejk Nov 26 '19 at 13:57
  • Thanks for the comment. Could you please give me an example on how to match MS docs with VCL ones? – UnDiUdin Nov 26 '19 at 14:05

1 Answers1

12

Just from inspecting the clipboard I could see at least 2 useful formats:

FileName (Ansi) and FileNameW (Unicode) which hold the file name copied to the clipboard. So basically you could register one of then (or both) with RegisterClipboardFormat and then retrieve the information you need. e.g.

uses Clipbrd;

var
  CF_FILE: UINT;

procedure TForm1.FormCreate(Sender: TObject);
begin
  CF_FILE := RegisterClipboardFormat('FileName');
end;

function ClipboardGetAsFile: string;
var
  Data: THandle;
begin
  Clipboard.Open;
  Data := GetClipboardData(CF_FILE);
  try
    if Data <> 0 then
      Result := PChar(GlobalLock(Data)) else
      Result := '';
  finally
    if Data <> 0 then GlobalUnlock(Data);
    Clipboard.Close;
  end;
end;

procedure TForm1.Button1Click(Sender: TObject);
begin
  if Clipboard.HasFormat(CF_FILE) then
    ShowMessage(ClipboardGetAsFile);
end;

Once you have the file name, just get it's size or other properties you want.
Note: The above was tested in Delphi 7. for Unicode versions of Delphi use the FileNameW format.

An alternative and more practical way (also useful for multiple files copied) is to register and handle the CF_HDROP format.

Here is an example in Delphi: How to paste files from Windows Explorer into your application

kobik
  • 21,001
  • 4
  • 61
  • 121
  • Thanks for the sample, i tried it but if i have a file in the clipboard i get [Content] 㩄瑜浥屰敖敮潴瀮杮꬀ꮫꮫꮫﺫﻮﻮ – UnDiUdin Nov 27 '19 at 11:12
  • I tried registering FileNameW and that one gives me the correct path to the copied file – UnDiUdin Nov 27 '19 at 11:13
  • 3
    @LaBracca, That was because you have Unicode Delphi version and I tested in Delphi 7 (Ansi, Non-Unicode). so in order to use the `FileName` format you need to replace `PChar` -> `PAnsiChar` and `string` -> `AnsiString`. In any case using `FileNameW` makes much more sense in a Unicode version/environment. With all that said I would personally go for the `CF_HDROP` since it can also process multiple files and you can't assume that a user only copied a single file. (`FileNameW` format will return the first one in the list in that case) – kobik Nov 27 '19 at 13:28