delphi 如何加载带有Windows剪贴板中复制的文件的流

41ik7eoe  于 2023-03-08  发布在  Windows
关注(0)|答案(1)|浏览(134)

我已经将一个文件复制到Windows剪贴板中(只需单击鼠标右键,复制)。我想加载一个TStream后代,其中包含当前存储在剪贴板中的文件。

uses
  Classes, Clipbrd;

MyStream := TMemoryStream.Create;
try
  //here I would like to load the clipboard file into MyStream
finally
  MyStream.Free;
end;
1qczuiv0

1qczuiv01#

当您将文件从硬盘复制到剪贴板时,它只会以CF_HDROP复制文件的完整路径和文件名。您可以使用DragQueryFile()函数读取文件名,例如:

uses
  Classes, Clipbrd, ShellAPI;

var
  hDrop: THandle
  MyStream: TMemoryStream;
  Files: TStringList;
  NumFiles, FileIdx: DWORD;
  FileName: array[0..MAX_PATH] of Char;
  I: Integer;
begin
  Files := TStringList.Create;
  try
    Clipboard.Open;
    try
      if Clipboard.HasFormat(CF_HDROP) then
      begin
        // DO NOT free this handle, the clipboard owns it!
        hDrop := Clipboard.GetAsHandle(CF_HDROP);
        NumFiles := DragQueryFile(hDrop, $FFFFFFFF, nil, 0);
        if NumFiles <> 0 then
        begin
          for FileIdx := 0 to NumFiles-1 do
          begin
            if DragQueryFile(hDrop, FileIdx, FileName, MAX_PATH) <> 0 then
              Files.Add(FileName);
          end;
        end;
      end;
    finally
      Clipboard.Close;
    end;
    for I := 0 to Files.Count-1 do
    begin
      MyStream := TMemoryStream.Create;
      try
        MyStream.LoadFromFile(Files[I]);
        MyStream.Position := 0;
        // use MyStream as needed...
      finally
        MyStream.Free;
      end;
    end;
  finally
    Files.Free;
  end;
end;

相关问题