TMemo.Lines.Insert 與 TRichEdit.Lines.Insert 僅能「插入新行」,無法在游標所在行內插入文字。
利用 SelText 屬性:將游標位置的選取長度設為 0,再指派 SelText 即可在游標處插入字串。
procedure InsertAtCursor(Memo: TMemo; const Text: string);
begin
// 確保無選取區塊
Memo.SelLength := 0;
// 在游標處插入
Memo.SelText := Text;
end;
// 使用範例
procedure TForm1.Button1Click(Sender: TObject);
begin
InsertAtCursor(Memo1, '插入的文字');
end;
SelLength := 0 取消任何現有選取,游標變為插入點。SelText := '...' 會將字串插入游標位置,並自動更新游標位置至插入文字之後。TEdit、TMaskEdit、TRichEdit 等具備 SelText 屬性的編輯控制項。procedure InsertAtCursorKeepPos(Memo: TMemo; const Text: string);
var
StartPos: Integer;
begin
StartPos := Memo.SelStart;
Memo.SelLength := 0;
Memo.SelText := Text;
Memo.SelStart := StartPos; // 游標回到插入點原位
end;