Han*_*ant 37
是的,您必须创建一个自定义文本框,以便检测它是否滚动.诀窍是将滚动消息传递给另一个文本框,以便它同步滚动.这真的只适用于其他文本框大小相同且行数相同的情况.
在项目中添加一个新类并粘贴下面显示的代码.编译.将两个新控件从工具箱顶部拖放到表单上.将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);
}
Run Code Online (Sandbox Code Playgroud)
你可以改变这一行:
if (m.Msg == 0x115) && !scrolling && Buddy != null && Buddy.IsHandleCreated)
Run Code Online (Sandbox Code Playgroud)
对此:
if ((m.Msg == 0x115 || m.Msg==0x20a) && !scrolling && Buddy != null && Buddy.IsHandleCreated)
Run Code Online (Sandbox Code Playgroud)
并且它也支持使用鼠标滚轮滚动.