How can I sync the scrolling of two multiline textboxes?
Solution 1:
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);
}
Solution 2:
You can change this line:
if (m.Msg == 0x115) && !scrolling && Buddy != null && Buddy.IsHandleCreated)
to this:
if ((m.Msg == 0x115 || m.Msg==0x20a) && !scrolling && Buddy != null && Buddy.IsHandleCreated)
and it will support scrolling with the mouse wheel as well.