Search code examples
delphiclipboardfilesizedelphi-10-seattle

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.


Solution

  • 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