如何在 C# (WinForms) 中同步两个多行文本框的滚动?
当您在文本框 A 中向上/向下滚动一行时,文本框 B 也应该向上/向下滚动。 反之亦然。
这是否可以在没有自定义控件的情况下实现?
最佳答案
是的,您必须创建一个自定义文本框以便检测它是否滚动。诀窍是将滚动消息传递给另一个文本框,以便它同步滚动。只有当其他文本框大小相同且行数相同时,这才有效。
向您的项目添加一个新类并粘贴如下所示的代码。编译。将工具箱顶部的两个新控件拖放到窗体上。将 Buddy 属性设置为两个上的另一个控件。运行,在它们中键入一些文本,然后在拖动滚动条时观察它们同步滚动。
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);
}
关于c# - 如何同步两个多行文本框的滚动?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3823188/