Tuesday 8 December 2009

[Code] Delphi Copying To and From TRichEdit

At work we have been looking at providing basic text editor facilities to some of our users.
After looking for some third party components we decided to use the built in Win32 palette TRichEdit component instead.

Below is the code we used to insert Rich Text Format text from a database blob field into a TRichEdit component.

try
MS := TMemoryStream.Create; try TBlobField(CdsXXXReason).SaveToStream(MS);
MS.Position := 0;
RichXXX.Lines.LoadFromStream(MS);
finally
FreeAndNil(MS);
end;
And then the code to save Rich Text Format text from a TrichEdit component to a database blob field
MS := TMemoryStream.Create();
try
CdsLabComment.Edit;
RichLabComment.Lines.SaveToStream(MS);
MS.Position := 0;
CdsXXXReason.LoadFromStream(MS);
CdsXXX.Post;
CdsXXX.ApplyUpdates(0);
finally
FreeAndNil(MS);
end;
Finally we needed to send the Rich Text Format text from the database to a word document.
MS := TMemoryStream.Create;
SlRichXXX := TStringList.Create;
try
TBlobField(CdsXXXReason).SaveToStream(MS);
MS.Position := 0;
SlRichComment.LoadFromStream(MS);
StrXXX := SlRichXXX.GetText;
RTFtoClipboard( StrXXX, StrXXX);
AppWord.Selection.Paste;
finally
MS.Free;
SlRichXXX.Free;
end;
Below is the required RTFtoClipboard procedure.
procedure RTFtoClipboard(txt: string; rtf: string);
var
Data: Cardinal;
CF_RTF : Word;
begin
CF_RTF := 0;
with Clipboard do
begin
CF_RTF := RegisterClipboardFormat('Rich Text Format');
Data := GlobalAlloc(GHND or GMEM_SHARE, Length(rtf)*SizeOf(Char) + 1);
if Data <> 0 then
try
StrPCopy(GlobalLock(Data), rtf);
GlobalUnlock(Data);
Open;
try
AsText := txt;
SetAsHandle(CF_RTF, Data);
finally
Close;
end;
except
GlobalFree(Data);
end;
end;

Hope this helps someone