如何在保持比率的两个RichTextBox中同步滚动?

问题描述 投票:1回答:1

我在这里找到了一个代码,在StackOverflow本身:How can I sync the scrolling of two multiline textboxes?

它工作正常,但我想要一个比例滚动。这意味着,如果我有两个RichTextBoxesRichTextBox1有10行,RichTextBox2有100行,所以当我在RichTextBox1滚动时,它会在RichTextBox2中跳过10行每1行滚动,如果我在RichTextBox2滚动它会滚动1行在RichTextBox1RichTextBox2每10行。

我认为这是可能的。

c# .net scroll richtextbox
1个回答
1
投票

肯定有更好的方法来做到这一点(没有干预选择)但这似乎有效:

class myRTB : RichTextBox
{
    public myRTB()
    {
        this.Multiline = true;
        this.ScrollBars = RichTextBoxScrollBars.Vertical;
    }

    public myRTB Buddy { get; set; }

    private static bool scrolling;   // In case buddy tries to scroll us
    protected override void WndProc(ref Message m)
    {
        base.WndProc(ref m);
        // Trap WM_VSCROLL message and pass to buddy
        if (m.Msg == 0x115 && !scrolling && Buddy != null && Buddy.IsHandleCreated)
        {
            scrolling = true;
            synchTopLineRel(Buddy);
            scrolling = false;
        }
    }

    void synchTopLineRel(RichTextBox rtb)
    {
        int i0 = GetCharIndexFromPosition(Point.Empty);
        int i1 = GetLineFromCharIndex(i0);
        int i2 = (int)(i1 * Buddy.Lines.Length / Lines.Length);
        // the rest scrolls to line # i2..:
        int bss = Buddy.SelectionStart;
        int bsl = Buddy.SelectionLength;
        Buddy.SelectionStart = Buddy.GetFirstCharIndexFromLine(i2);
        Buddy.ScrollToCaret();
        Buddy.SelectionStart = bss;
        Buddy.SelectionLength = bsl;
    }
}

请注意,它没有错误检查,并且将进行非常简单的计算。它不适用于:

  • 具有不同字体的RTB
  • RTB具有不同的大小

特别是如果你需要编写qazxsw poi事件的代码,你更愿意用适当的qazxsw poi调用替换滚动。可能的qazxsw poi

© www.soinside.com 2019 - 2024. All rights reserved.