首页  编辑  

根据格式名字从剪切板获取数据

Tags: /超级猛料/OS.操作系统/Clipboard.剪贴板/   Date Created:
根据格式名字从剪切板获取数据
function GetDataFromClipboardByFormat(Format: string): string;
var
  i, size: Integer;
  cfNum: Integer;
  cfFmt: Word;
  cfName: array [0 .. 1024] of char;
  cfData: THandle;
  cfMem: Pointer;
begin
  // Get Data From Clipboard by format name, format name can be
  // - HTML Format
  // - Text
  // - DataObject
  // - ...
  Result := '';
  if not OpenClipboard(GetActiveWindow) then
    Exit;
  try
    cfNum := CountClipboardFormats;
    cfFmt := EnumClipboardFormats(0);
    for i := 0 to cfNum - 1 do
    begin
      GetClipboardFormatName(cfFmt, cfName, 200);
      if SameText(cfName, Format) then
      begin
        cfData := GetClipboardData(cfFmt);
        try
          cfMem := GlobalLock(cfData);
          size := GlobalSize(cfData);
          SetLength(Result, size);
          Move(cfMem^, Result[1], size);
        finally
          GlobalUnlock(cfData);
        end;
        Break;
      end; // End if
      cfFmt := EnumClipboardFormats(cfFmt);
    end;
  finally
    CloseClipboard;
  end;
end;

function GetClipboardAs HTML: string;
var
  HTML: string;
  index: Integer;
begin
  HTML := GetDataFromClipboardByFormat('HTML Format');
  HTML := Utf8ToAnsi(HTML); // 剪切板中的HTML为UTF8格式编码!
  index := Pos('SourceURL:', HTML);
  while (index < Length(HTML)) and (index > 0) and (HTML[index] <> #10) do
    Inc(Index);
  Inc(index);
  Result := Copy(HTML, index, Length(HTML) - index + 1);
end;