Delphi Clipboard: Read file properties of a file copied
Asked Answered
R

1

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.

Redound answered 26/11, 2019 at 13:38 Comment(2)
You can read this articles: article 1 and article 2. VCL's docs on TClipboard not very useful in your case.Skelp
Thanks for the comment. Could you please give me an example on how to match MS docs with VCL ones?Redound
D
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

Drapery answered 26/11, 2019 at 14:59 Comment(3)
Thanks for the sample, i tried it but if i have a file in the clipboard i get [Content] 㩄瑜浥屰敖敮潴瀮杮꬀ꮫꮫꮫﺫﻮﻮRedound
I tried registering FileNameW and that one gives me the correct path to the copied fileRedound
@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)Drapery

© 2022 - 2024 — McMap. All rights reserved.