Search code examples
freepascallazarus

TRichMemo - LoadRichText not working


I am trying to save the contents of a TRichMemo to TMemoryStream, and then be able to load the formatted data back from the stream into the rich memo.

The problem is LoadRichText is failing for some reason. I know the data is been saved to my stream because I can actually save it fo file as rtf and view it externally.

This is basically what I have:

var
  FMyStream: TMemoryStream;

To save:

RichMemo1.SaveRichText(FMyStream);

To load:

FMyStream.Seek(0, soBeginning);
if not RichMemo1.LoadRichText(FMyStream) then
  raise Exception.Create('Failed to load data from stream.');

As I said the data is saved to stream correctly, but trying to load into the rich memo is hitting my exception everytime.

What could be the problem?

The code for the LoadRichText function is:

function TCustomRichMemo.LoadRichText(Source: TStream): Boolean;
begin
  if Assigned(Source) and HandleAllocated then begin
    Result := TWSCustomRichMemoClass(WidgetSetClass).LoadRichText(Self, Source);
    if not Result and Assigned(RTFLoadStream) then begin
      Self.Lines.BeginUpdate;
      Self.Lines.Clear;
      Result:=RTFLoadStream(Self, Source);
      Self.Lines.EndUpdate;
    end;
  end else
    Result := false;
end;

and SaveRichText code:

function TCustomRichMemo.SaveRichText(Dest: TStream): Boolean;
begin
  if Assigned(Dest) and HandleAllocated then begin
    Result := TWSCustomRichMemoClass(WidgetSetClass).SaveRichText(Self, Dest);
    if not Result and Assigned(RTFSaveStream) then
      Result:=RTFSaveStream(Self, Dest);
  end else
    Result := false;
end;

Thanks.


Solution

  • Ok, I found the solution to my problem.

    At first I created a simple test project and LoadRichText and SaveRichText worked, which meant the problem was within my code somewhere...

    My stream is declared in a class in a separate unit. In another form I have my rich memo control, when the form is closed the data is saved to the stream, that part I knew worked because I could save it to file and view it externally.

    The problem was when I was creating the form that contains my rich memo, I was calling LoadRichText from the FormCreate event. So I moved it into FormActivate and now it works without error.