2008. április 23., szerda

Retrieve clipboard data in RTF tokens


Problem/Question/Abstract:

I'm trying to retrieve clipboard data in RTF tokens, and I can't figure out how to do it. Here's the scenario: 1. Create rich text in (eg) WordPad, including bold, italics etc., 2. Copy that to the clipboard., 3. Paste it into a TRichEdit. The pasted data includes all the formatting info. However, if I try to get that data off the clipboard myself, using Clipboard.AsText, or getting a handle to it with CF_TEXT, what I get is plain text, minus the formatting. It seems to me there should be a way to get RTF tokens from the clipboard, but neither the Delphi docs nor the MS documentation lists any format that could include rich text. There is no such format as CF_RICHTEXT. Anybody know how I can do this? Am I completely wrong to assume that RTF tokens are even being passed through the clipboard in the above scenario?

Answer:

uses
  RichEdit;

function GetRawRTFFromClipboard: string;
var
  H: THandle;
  TextPtr: PChar;
  CurrentFormat: Integer;
  NameLen: DWord;
  NameStr: string;
begin
  Result := '';
  ClipBoard.Open;
  try
    CurrentFormat := EnumClipboardFormats(0);
    while CurrentFormat <> 0 do
    begin
      NameLen := 1024;
      SetLength(NameStr, NameLen);
      NameLen := GetClipboardFormatName(CurrentFormat, PChar(NameStr), NameLen);
      SetLength(NameStr, NameLen);
      if CompareText(NameStr, CF_RTF) = 0 then
        Break;
      CurrentFormat := EnumClipboardFormats(CurrentFormat);
    end;
    if CurrentFormat = 0 then
      raise Exception.Create('Data on clipboard is not RTF');
    H := Clipboard.GetAsHandle(CurrentFormat);
    TextPtr := GlobalLock(H);
    Result := StrPas(TextPtr);
    GlobalUnlock(H);
  finally
    Clipboard.Close;
  end;
end;

Nincsenek megjegyzések:

Megjegyzés küldése