在尝试了许多不能给出准确结果的不同解决方案后,我受到了这个解决方案的启发:
Convert RTF to HTML and HTML to RTF.
我们的想法是,TWebBrowser控件(在设计/编辑模式下)可以在从剪贴板粘贴时正确处理和转换Rich文本格式.
uses SHDocVw,MSHTML;
function ClipboardToHTML(AParent: TWinControl): WideString;
var
wb: TWebBrowser;
function WaitDocumentReady: Boolean;
var
StartTime: DWORD;
begin
StartTime := GetTickCount;
while wb.ReadyState <> READYSTATE_COMPLETE do
begin
Application.HandleMessage;
if GetTickCount >= StartTime + 2000 then // time-out of max 2 sec
begin
Result := False; // time-out
Exit;
end;
end;
Result := True;
end;
begin
Result := '';
wb := TWebBrowser.Create(nil);
try
wb.Silent := True;
wb.Width := 0;
wb.Height := 0;
wb.Visible := False;
TWinControl(wb).Parent := AParent;
wb.HandleNeeded;
if wb.HandleAllocated then
begin
wb.Navigate('about:blank');
(wb.Document as IHTMLDocument2).designMode := 'on';
if WaitDocumentReady then
begin
(wb.Document as IHTMLDocument2).execCommand('Paste',False,0);
Result := (wb.Document as IHTMLDocument2).body.innerHTML;
end;
end;
finally
wb.Free;
end;
end;
procedure TForm1.Button1Click(Sender: TObject);
begin
RichEdit1.SelectAll;
RichEdit1.CopyToClipboard;
ShowMessage(ClipboardToHTML(Self));
end;