How to transfer text from a TMemo component to a Rave TMemoBuf

Category

Code Based - General

Question

How to transfer text from a TMemo component to a Rave TMemoBuf

Solution

A TMemo component does not provide an easy and consistent method to access all of its text. Below is a method that will work with both large and small amounts of text. The first step is to create a PChar variable using StrAlloc and TMemo.GetTextLen and then load the text into this PChar with TMemo.GetTextBuf. After that you can use TMemoBuf.SetData to load the PChar into the memo buffer. Make sure to deallocate the PChar when finished.

Example:

{ Create a TMemoBuf from a TMemo component }
  function CreateMemoBufFromMemo(Memo: TMemo): TMemoBuf;

  var
    PCharVar: PChar;
    MemoBuf: TMemoBuf;

  begin { CreateMemoBufFromMemo }
    MemoBuf := TMemoBuf.Create;
    PCharVar := StrAlloc(Memo.GetTextLen);
    try
      Memo.GetTextBuf(PCharVar,Memo.GetTextLen);
      MemoBuf.SetData(PCharVar^,StrLen(PCharVar));
    finally
      StrDispose(PCharVar);
    end; { tryf }
    Result := MemoBuf;
  end;  { CreateMemoBufFromMemo }