首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> 更多程式語言 >> Delphi

Delphi 實現 TMemo/TRichEdit 真正的游標位置插入文字

     編輯:Delphi

問題

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;
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved