我正在尝试编写一个包装类TRichEdit
,可以将 RTF 编码和解码到纯文本/从纯文本解码。
这是我到目前为止所写的:
type
TRTF = class
private
FRichEdit : TRichEdit;
procedure SetText(const AText: string);
function GetText: string;
class function Convert(const AInput: string; AEncode: Boolean): string; inline; static;
public
constructor Create;
destructor Destroy; override;
class function Decode(const AInput: string): string; static;
class function Encode(const AInput: string): string; static;
end;
constructor TRTF.Create;
begin
FRichEdit := TRichEdit.CreateParented(HWND_MESSAGE);
end;
destructor TRTF.Destroy;
begin
FRichEdit.Free;
inherited;
end;
function TRTF.GetText: string;
var
Stream: TStringStream;
begin
if FRichEdit.PlainText then begin
Stream := TStringStream.Create('', TEncoding.ANSI);
end else begin
Stream := TStringStream.Create('', TEncoding.ASCII);
end;
try
FRichEdit.Lines.SaveToStream(Stream, Stream.Encoding);
Result := Stream.DataString;
finally
Stream.Free;
end;
end;
procedure TRTF.SetText(const AText: string);
var
Stream: TStringStream;
begin
if FRichEdit.PlainText then begin
Stream := TStringStream.Create(AText, TEncoding.ANSI);
end else begin
Stream := TStringStream.Create(AText, TEncoding.ASCII);
end;
try
Stream.Seek(0, TSeekOrigin.soBeginning);
FRichEdit.Lines.LoadFromStream(Stream);
finally
Stream.Free;
end;
end;
class function TRTF.Convert(const AInput: string; AEncode: Boolean): string;
var
RTF: TRTF;
begin
RTF := TRTF.Create;
try
RTF.FRichEdit.PlainText := AEncode;
RTF.SetText(AInput);
RTF.FRichEdit.PlainText := not AEncode;
Result := RTF.GetText;
finally
RTF.Free;
end;
end;
class function TRTF.Encode(const AInput: string): string;
begin
Result := Convert(AInput, True);
end;
class function TRTF.Decode(const AInput: string): string;
begin
Result := Convert(AInput, False);
end;
对于可以由用户默认 ANSI 代码页表示的所有内容,这似乎工作得相当好。
?
但是,对于其他字符,它会失败(将它们转换为)。
有没有一种简单的方法可以在我的代码中启用正确的 Unicode 处理?
当设置为时,我尝试使用TEncoding.Unicode
andTEncoding.UTF8
作为编码,但这不起作用。TStringStream
TRichEdit
PlainText := True