Ron
Ron

Reputation: 391

How to select a line in a RichTextBox on a mouse click?

I have a read-only RichTextBox in my user interface. I want to make it so that when I click on a line of text with the mouse it selects or highlights the entire line. Just that one line that was clicked.

How do you do this?

Upvotes: 0

Views: 7640

Answers (2)

Hans Passant
Hans Passant

Reputation: 941317

RichTextBox has all the methods you need, you just need multiple of them. First you need to map the mouse position to a character index:

Private Sub RichTextBox1_MouseDown(ByVal sender As Object, ByVal e As MouseEventArgs)
    Dim box = DirectCast(sender, RichTextBox)
    Dim index = box.GetCharIndexFromPosition(e.Location)

Then you need to map the character index to a line:

    Dim line = box.GetLineFromCharIndex(index)

Then you need to find out where the line starts:

    Dim lineStart = box.GetFirstCharIndexFromLine(line)

Then you need to find out where it ends, which is the start of the next line minus one:

    Dim lineEnd = box.GetFirstCharIndexFromLine(line + 1) - 1

Then you need to make the selection:

    box.SelectionStart = lineStart
    box.SelectionLength = lineEnd - lineStart

Summarizing:

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) - 1
    box.SelectionStart = lineStart
    box.SelectionLength = lineEnd - lineStart
End Sub

Upvotes: 3

Krishanu Dey
Krishanu Dey

Reputation: 6406

Just use the following code in click event handler

SendKeys.Send("{HOME}+{END}")

Upvotes: 0

Related Questions