嘗試了許多沒有給出準確結果的不同解決方案后,我受到了這裡解決方案的啟發: 將RTF轉換為HTML格式,HTML轉換為RTF格式。
它的思想是,TWebBrowser 控制項( 在設計/編輯模式中) 在從剪貼板粘貼時可以處理和轉換正確的文本格式。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;