How to set scroll position of rich text box control?

痞子三分冷 提交于 2019-12-13 16:08: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.

来源:https://stackoverflow.com/questions/11966037/how-to-set-scroll-position-of-rich-text-box-control

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!