【问题标题】:Winforms RichTextBox: How can I scroll the caret to the middle of the RichTextBox?Winforms RichTextBox:如何将插入符号滚动到 RichTextBox 的中间?
【发布时间】:2009-11-20 21:38:02
【问题描述】:
【问题讨论】:
标签:
.net
winforms
richtextbox
【解决方案1】:
如果富文本框在_rtb中,那么可以得到可见行数:
public int NumberOfVisibleLines
{
get
{
int topIndex = _rtb.GetCharIndexFromPosition(new System.Drawing.Point(1, 1));
int bottomIndex = _rtb.GetCharIndexFromPosition(new System.Drawing.Point(1, _rtb.Height - 1));
int topLine = _rtb.GetLineFromCharIndex(topIndex);
int bottomLine = _rtb.GetLineFromCharIndex(bottomIndex);
int n = bottomLine - topLine + 1;
return n;
}
}
然后,如果您想将插入符号滚动到距富文本框顶部 1/3 处,请执行以下操作:
int startLine = _rtb.GetLineFromCharIndex(ix);
int numVisibleLines = NumberOfVisibleLines;
// only scroll if the line to scroll-to, is larger than the
// the number of lines that can be displayed at once.
if (startLine > numVisibleLines)
{
int cix = _rtb.GetFirstCharIndexFromLine(startLine - numVisibleLines/3 +1);
_rtb.Select(cix, cix+1);
_rtb.ScrollToCaret();
}