Reputation: 109
I want to add an string into specified place of a Memo Edit in delphi, how can I do this? I mean I want to know where the mouse cursor is within TMemo, and then add a string to this position. Is that possible?
Upvotes: 1
Views: 9759
Reputation: 56
It's very simple (NGLN's answer):
MyMemo.SelText := MyString;
Upvotes: 0
Reputation: 54812
You can use EM_CHARFROMPOS
to determine the character position of where the mouse cursor points:
var
Pt: TPoint;
Pos: Integer;
begin
Pt := Memo1.ScreenToClient(Mouse.CursorPos);
if (Pt.X >= 0) and (Pt.Y >= 0) then begin
Pos := LoWord(Memo1.Perform(EM_CHARFROMPOS, 0, MakeLong(Pt.x, Pt.Y)));
Memo1.SelLength := 0;
Memo1.SelStart := Pos;
Memo1.SelText := '.. insert here ..';
end;
end;
Upvotes: 9
Reputation: 51
If you want to place your string at the caret position of your memo you can use the following code:
procedure TForm1.InsertStringAtcaret(MyMemo: TMemo; const MyString: string);
begin
MyMemo.Text :=
// copy the text before the caret
Copy(MyMemo.Text, 1, MyMemo.SelStart) +
// then add your string
MyString +
// and now ad the text from the memo that cames after the caret
// Note: if you did have selected text, this text will be replaced, in other words, we copy here the text from the memo that cames after the selection
Copy(MyMemo.Text, MyMemo.SelStart + MyMemo.SelLength + 1, length(MyMemo.Text));
// clear text selection
MyMemo.SelLength := 0;
// set the caret after the inserted string
MyMemo.SelStart := MyMemo.SelStart + length(MyString) + 1;
end;
Upvotes: 4
Reputation: 121759
You can add a string to the bottom of the ".Lines" member: MyMemo.Lines.add('MyString')
.
You can also replace a string in any (already existing) position in "Lines" you want: MyMemo.Lines[2] := 'MyString'
.
Finally, you can insert anywhere you want: MyMemo.Lines.Insert(2, 'MyString')
Upvotes: 0