Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Delphi Clipboard: Read file properties of a file copied

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.

like image 231
LaBracca Avatar asked Nov 26 '19 13:11

LaBracca


1 Answers

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

like image 164
kobik Avatar answered Nov 15 '22 10:11

kobik