How to set scroll position of rich text box contro

2019-07-16 16:31发布

问题:

I am using 2 Rich Text Boxes on winforms 4 (customRTB1 and customRTB2). Both of the rtb's have same text. What I want to achieve is, when one rtb (customRTB1) is scrolled down, the other rtb (customRTB2) also should be scrolled to exactly same position as customRTB1. I attempted this:

public class CustomRTB : RichTextBox
    {
        #region API Stuff
        [DllImport("user32.dll", CharSet = CharSet.Auto)]
        public static extern int GetScrollPos(IntPtr hWnd, int nBar);

        [DllImport("user32.dll")]
        public static extern int SetScrollPos(IntPtr hWnd, int nBar, int nPos, bool bRedraw);

        private const int SB_HORZ = 0x0;
        private const int SB_VERT = 0x1;
        #endregion
        public int HorizontalPosition
        {
            get { return GetScrollPos((IntPtr)this.Handle, SB_HORZ); }
            set { SetScrollPos((IntPtr)this.Handle, SB_HORZ, value, true); }
        }

        public int VerticalPosition
        {
            get { return GetScrollPos((IntPtr)this.Handle, SB_VERT); }
            set { SetScrollPos((IntPtr)this.Handle, SB_VERT, value, true); }
        }
    }

Using HorizontalPosition and VerticalPosition I could move the scroll bar of SECOND rtb as follows:

private void customRTB1_VScroll(object sender, EventArgs e)
{
          customRTB2.VerticalPosition = customRTB1.VerticalPosition;
}

This moves the scroll bar of second rtb to the position of first rtb, however, it DOES NOT move the text at all! So how to make this second rtb to show the corresponding text according to the scroll bar's position? Mainly, I want every activity happening (editing, scrolling etc)of first rtb to repeat on second rtb. I know I am very close to the solution. Please help.