click and select line (hightlight) in Delphi TMemo


When I click with the mouse on a line of text of a memo, I want that line to be selected (highlighted). Is this possible?


Selecting text in a Delphi TMemo component is done by setting the SelStart and SelLength properties.

If you want to select the entire current line with a mouse click, start by creating an OnClick event handler for the Memo.
In the event handler:

1. Find out the number of the line whith the "caret" (text cursor), by sending an EM_LINEFROMCHAR message to the Memo.

2. Set the Memo's SelStart to the "character index" of the current line. The character index is the number of characters from the beginning of the Memo to the beginning of the specified line. You get it by sending an EM_LINEINDEX message to the Memo.

3. Set the Memo's SelLength to the length of the current line.

Here's a source code example:

procedure TForm1.Memo1Click(Sender: TObject);
  CurrentLine: integer;
  CurrentLine := Memo1.Perform(EM_LINEFROMCHAR, -1, 0);
  Memo1.SelStart := Memo1.Perform(EM_LINEINDEX, CurrentLine, 0);
  Memo1.SelLength := Length(Memo1.Lines[CurrentLine]);