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

夙愿已清 提交于 2019-12-11 18:39:59

问题


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?


回答1:


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



回答2:


Just use the following code in click event handler

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


来源:https://stackoverflow.com/questions/10746121/how-to-select-a-line-in-a-richtextbox-on-a-mouse-click

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!