views:

109

answers:

2

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?

+6  A: 

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;
500 - Internal Server Error
You can do the same with the memo's `SelText` property.
Rob Kennedy
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
@Per Larsen: Perfect, that's exactly what I was looking for. Thanks.
Brian Frost
+1  A: 

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
I know about Strings property, but I have no idea what characters will arrive, and there may be only 1.
Brian Frost
@Brian Frost: why does it matter what characters will arrive and if it's only one?
The_Fox