Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I sync the scrolling of two multiline textboxes?

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 the other way around.

Is this achievable without custom controls?

like image 555
lesderid Avatar asked Sep 29 '10 15:09

lesderid


People also ask

How do you create a scrolling text box?

Right-click the control for which you want to set a text-scrolling option, and then click Control Properties on the shortcut menu. Click the Display tab. In the Scrolling list, click the text-scrolling option that you want.

How do I make labels scrollable?

Place a panel in location where you want the label to be, set it's AutoScroll property to true. Then place the label in the panel, anchor it and set it's AutoSize property to true. This will make the panel provide the scroll bars if the label's text extends outside of the panel.


1 Answers

Yes, you'll have to create a custom text box so you can detect it scrolling. The trick is to pass the scroll message to the other text box so it will scroll in sync. This really only works well when that other text box is about the same size and has the same number of lines.

Add a new class to your project and paste the code shown below. Compile. Drop two of the new controls from the top of the toolbox onto your form. Set the Buddy property to the other control on both. Run, type some text in both of them and watch them scroll in sync as you drag the scrollbar.

using System;
using System.Windows.Forms;
using System.Runtime.InteropServices;

class SyncTextBox : TextBox {
    public SyncTextBox() {
        this.Multiline = true;
        this.ScrollBars = ScrollBars.Vertical;
    }
    public Control 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;
            SendMessage(Buddy.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);
}
like image 165
Hans Passant Avatar answered Oct 02 '22 19:10

Hans Passant