RichTextBox: highlight a line on click
Handle the MouseDown event of a WinForms RichTextBox to select the whole line under the mouse.
To highlight the line a user clicks in a RichTextBox, handle the MouseDown event. Work out which character is under the mouse, find its line, then select from the start of that line to the start of the next.
vb
Private Sub RichTextBox1_MouseDown(ByVal sender As Object, ByVal e As MouseEventArgs) Handles RichTextBox1.MouseDown
Dim box = DirectCast(sender, RichTextBox)
Dim index = box.GetCharIndexFromPosition(e.Location)
Dim line = box.GetLineFromCharIndex(index)
Dim lineStart = box.GetFirstCharIndexFromLine(line)
Dim lineEnd = box.GetFirstCharIndexFromLine(line + 1)
If lineEnd = -1 Then
lineEnd = box.TextLength
End If
box.SelectionStart = lineStart
box.SelectionLength = lineEnd - lineStart
End Sub
GetFirstCharIndexFromLine returns -1 when there is no next line, so on the last line the selection runs to the end of the text.