C#: Synchronize Scroll Position of two RichTextBoxes?

前端 未结 5 591
失恋的感觉
失恋的感觉 2020-11-30 10:00

In my application\'s form, I have two RichTextBox objects. They will both always have the same number of lines of text. I would like to \"synchronize\" the vert

5条回答
  •  一向
    一向 (楼主)
    2020-11-30 11:02

    I did this for a small project a while ago, and here's the simplist solution I found.

    Create a new control by subclassing RichTextBox:

       public class SynchronizedScrollRichTextBox : System.Windows.Forms.RichTextBox
        {
            public event vScrollEventHandler vScroll;
            public delegate void vScrollEventHandler(System.Windows.Forms.Message message);
    
            public const int WM_VSCROLL = 0x115;
    
            protected override void WndProc(ref System.Windows.Forms.Message msg) {
                if (msg.Msg == WM_VSCROLL) {
                    if (vScroll != null) {
                        vScroll(msg);
                    }
                }
                base.WndProc(ref msg);
            }
    
            public void PubWndProc(ref System.Windows.Forms.Message msg) {
                base.WndProc(ref msg);
            }
        }     
    

    Add the new control to your form and for each control explicitly notify the other instances of the control that its vScroll position has changed. Somthing like this:

    private void scrollSyncTxtBox1_vScroll(Message msg) {
        msg.HWnd = scrollSyncTxtBox2.Handle;
        scrollSyncTxtBox2.PubWndProc(ref msg);
    }
    

    I think this code has problems if all the 'linked' controls don't have the same number of displayable lines.

提交回复
热议问题