1

I have just found this code to get files from the clipboard and it works fine, but I would like to make it a Boolean function so that I know it succeeded. What do I need to test to see if it has the file(s) on the clipboard and that all is OK?

USES Clipbrd, shellapi;

// procedure GetFileNameFromClipboard(oSL : TStringlist);
function GetFileNameFromClipboard(oSL : TStringlist) : Boolean;
var
      f: THandle;
      buffer: array [0..MAX_PATH] of Char;
      i, c: Integer;
begin
      Result:=False;
      if NOT Clipboard.HasFormat(CF_HDROP) then exit;
      Clipboard.Open;
      f := Clipboard.GetAsHandle(CF_HDROP);
      if f <> 0 then 
      begin
         c := DragQueryFile(f, $FFFFFFFF, nil, 0);
         for i:=0 to c-1 do 
         begin
             buffer[0] := #0;
             DragQueryFile(f, i, buffer, SizeOf(buffer));
             oSL.Add(buffer);
         end;
      end;
      Clipboard.Close;
   Result:=???????
end;
Rob Kennedy
  • 161,384
  • 21
  • 275
  • 467
user2445336
  • 53
  • 1
  • 5
  • 2
    Set `Result` to be `True` if the function succeeds, or `False` otherwise. Watch out for that `exit`. Add some error checking where it is missing. Use `try/finally` to protect resources. – David Heffernan Jun 09 '13 at 16:21
  • @DavidHeffernan Thanks, I have edited the above prior to the Exit to set Result:=False; but, what would define "True?" Are you saying that if it gets past Clipboard.Close then the Result must be true? – user2445336 Jun 09 '13 at 17:25
  • @J.Gonzalez Thanks, but that is what I need to know - see my edit at David's comment. During the copy to the Clipboard, what indicates that the copy was successful and the File is now sitting there to be Pasted somewhere else? – user2445336 Jun 09 '13 at 17:29
  • 1
    @user2445336, DragQueryFile function returns a nonezero value if it was successful. – Peter Jun 09 '13 at 17:46
  • @PeterVonča Ah Ha! Thanks. That makes sense. I should have seen that with the "for i:=c to c-1" -- slap to my forehead :) – user2445336 Jun 09 '13 at 18:10

1 Answers1

4

Try something like this:

function GetFileNameFromClipboard(oSL : TStrings) : Boolean;
var
  f: THandle;
  buffer: array [0..MAX_PATH] of Char;
  S: string;
  i, c: UINT;
begin
  Result := False;
  Clipboard.Open;
  try
    f := Clipboard.GetAsHandle(CF_HDROP);
    if f = 0 then Exit;
    c := DragQueryFile(f, $FFFFFFFF, nil, 0);
    if c = 0 then Exit;
    for i := 0 to c-1 do 
    begin
      c := DragQueryFile(f, i, buffer, Length(buffer));
      if c <> 0 then begin
        SetString(s, buffer, c);
        oSL.Add(s);
        Result := True;
      end;
    end;
  finally
    Clipboard.Close;
  end;
end;
Remy Lebeau
  • 555,201
  • 31
  • 458
  • 770
  • 1
    +1 0..MAX_PATH-1 would be more normal but I'd probably dynamically allocate the buffer to cater for long filenames. That said, one wonders whether or not they would arrive with the \\?\ prefix. – David Heffernan Jun 09 '13 at 20:16