的WinForms RichTextBox的:我怎样才能滚动插入符RichTextBox的中间? [英] Winforms RichTextBox: How can I scroll the caret to the middle of the RichTextBox?

查看:163
本文介绍了的WinForms RichTextBox的:我怎样才能滚动插入符RichTextBox的中间?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想滚动一个RichTextBox,使插入符大约是在RichTextBox的中间。

I want to scroll a RichTextBox so that the caret is approximately in the middle of the RichTextBox.

喜欢的东西 RichTextBox.ScrollToCaret()< /一>,但我不想把插入符在最高层。

Something like RichTextBox.ScrollToCaret(), except I don't want to put the caret at the very top.

我看到了<一个href="http://stackoverflow.com/questions/1027910/winforms-screen-location-of-caret-position">Winforms:插入符位置的屏幕位置,当然也看到了Win32函数的 SetCaretPos()。但我不知道如何翻译的X,要求ÿ通过SetCaretPos入RichTextBox的线。

I saw Winforms: Screen Location of Caret Position, and of course also saw the Win32 function SetCaretPos(). But I'm not sure how to translate the x,y required by SetCaretPos into lines in the richtextbox.

推荐答案

如果富文本框是_rtb,那么你可以得到的可视行数:

If the rich text box is in _rtb, then you can get the number of visible lines:

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;
    }
}

然后,如果你想从RichTextBox的顶部滚动插入符号,比方说,方式的1/3,做到这一点:

Then, if you want to scroll the caret to, say, 1/3 of the way from the top of the richtextbox, do this:

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();
}

这篇关于的WinForms RichTextBox的:我怎样才能滚动插入符RichTextBox的中间?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆