4

I am using a TMemo to hold received characters from a serial port for viewing. As they arrive I am doing:

Memo1.Text := Memo1.Text + sReceivedChars;

This works fine but I presume it is rather inefficient, having to get the existing text before concatenating my few characters and then writing it back. I would really like a 'SendChars()' function or something similar. Is there a better way of simply adding a few characters on the end of the existing text?

Josh Crozier
  • 233,099
  • 56
  • 391
  • 304
Brian Frost
  • 13,334
  • 11
  • 80
  • 154

2 Answers2

8

I don't know if you think it's worthwhile, but you can do something like this:

procedure TForm1.Button1Click(Sender: TObject);
var
  index: Integer;
  NewText: string;
begin
  NewText := 'Append This';
  index := GetWindowTextLength (Memo1.Handle);
  SendMessage(Memo1.Handle, EM_SETSEL, index, index);
  SendMessage (Memo1.Handle, EM_REPLACESEL, 0, Integer(@NewText[1]));
end;
  • You can do the same with the memo's `SelText` property. – Rob Kennedy Aug 26 '10 at 23:09
  • 3
    Or use `Memo1.SelStart := Index; Memo1.SelText := NewText;` - these do the same thing under the hood. But using GetWindowTextLength is much better than Length(Memo1.Text) – Gerry Coll Aug 26 '10 at 23:18
2

If your text is in more than one line (strings of a the TStrings collection that is the actual type of the Lines property of the TMemo), then you could do this:

Memo1.Lines[Memo1.Lines.Count - 1] := Memo1.Lines[Memo1.Lines.Count - 1] + sReceivedChars;

So you add some chars to the last line (the last string in the string collection) of the memo, without taking the whole text into a single string.

SalvadorGomez
  • 552
  • 4
  • 15