How can I sync the scrolling of two multiline textboxes?

后端 未结 5 474
爱一瞬间的悲伤
爱一瞬间的悲伤 2020-11-30 07:57

How can I sync the scrolling of two multiline textboxes in C# (WinForms)?

When you scroll up/down a line in TextBox A, TextBox B should scroll up/down too. The same

5条回答
  •  没有蜡笔的小新
    2020-11-30 08:29

    Hans Passant's solution was awesome. However I needed to sync three text boxes not just two.

    So I modified it a little - but all credence should go to Hans, there's no way I would have even got close without his work - I thought I would post it back here in case others need the same.

    SyncBox class:

    using System;
    using System.Windows.Forms;
    using System.Runtime.InteropServices;
    
    class SyncTextBox : TextBox
    {
        public SyncTextBox()
        {
            this.Multiline = true;
            this.ScrollBars = ScrollBars.Vertical;
        }
    
        public Control[] Buddies { 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 (Buddies != null)
            {
                foreach (Control ctr in Buddies)
                {
                    if (ctr != this)
                    {
                        if ((m.Msg == 0x115 || m.Msg == 0x20a) && !scrolling && ctr.IsHandleCreated)
                        {
                            scrolling = true;
                            SendMessage(ctr.Handle, m.Msg, m.WParam, m.LParam);
                            scrolling = false;
                        }
                    }
                }
            }
        }
        [DllImport("user32.dll", CharSet = CharSet.Auto)]
        private static extern IntPtr SendMessage(IntPtr hWnd, int msg, IntPtr wp, IntPtr lp);
    }
    

    Then in the form initilizer:

    // add the required controls into scroll sync
    Control[] syncedCtrls = new Control[] { ctrl1, ctrl2, ..., ctrln };
    foreach (SyncTextBox ctr in syncedCtrls)
    {
        ctr.Buddies = syncedCtrls;
    }
    

提交回复
热议问题