如何通过鼠标单击在 RichTextBox 中选择一行? [英] How to select a line in a RichTextBox on a mouse click?
问题描述
我的用户界面中有一个只读 RichTextBox.我想让它当我用鼠标单击一行文本时,它会选择或突出显示整行.只是被点击的那一行.
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.
你是怎么做到的?
推荐答案
RichTextBox 拥有您需要的所有方法,您只需要其中的多个.首先需要将鼠标位置映射到字符索引:
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
然后您需要进行选择:
box.SelectionStart = lineStart
box.SelectionLength = lineEnd - lineStart
总结:
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
这篇关于如何通过鼠标单击在 RichTextBox 中选择一行?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!