Winforms RichTextBox: How can I determine how many lines of text are visible?

前端 未结 2 767
独厮守ぢ
独厮守ぢ 2021-01-11 17:10

I have a Winforms app containing a RichTextBox.

How can I determine how many lines of text are displayed, currently visible?

Reason: I want to scroll th

2条回答
  •  無奈伤痛
    2021-01-11 17:29

    Well, this isn't pretty, but it works for me. Basically I'm checking a point just inside the upper-left corner of the richtextbox and a point just inside the lower left corner of the textbox. You may have to adjust the point coordinates depending on how your richtextbox is displayed. Then I get the character index that is closest to each of those two points, and retrieve the line that it is on.

    Dim topIndex As Integer = RichTextBox1.GetCharIndexFromPosition(New Point(1, 1))
    Dim bottomIndex As Integer = RichTextBox1.GetCharIndexFromPosition(New Point(1, RichTextBox1.Height - 1))
    
    Dim topLine As Integer = RichTextBox1.GetLineFromCharIndex(topIndex)
    Dim bottomLine As Integer = RichTextBox1.GetLineFromCharIndex(bottomIndex)
    
    Dim numLinesDisplayed As Integer = bottomLine - topLine
    

    I tested it for richtextboxes with multiple sizes of fonts displayed, and it seems to work. I suspect that the answer that is returned will be off (too small) by one line if the last line of displayed text has a lot of white space under it and the next line is almost ready to be displayed. If you have a very tall richtextbox, with many lines, this shouldn't be a problem.

提交回复
热议问题