如何同步两个多行文本框的滚动? [英] How can I sync the scrolling of two multiline textboxes?

查看:13
本文介绍了如何同步两个多行文本框的滚动?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何在 C# (WinForms) 中同步两个多行文本框的滚动?

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

当您在 TextBox A 中向上/向下滚动一行时,TextBox B 也应该向上/向下滚动.反之亦然.

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?

推荐答案

是的,您必须创建一个自定义文本框,以便可以检测到它在滚动.诀窍是将滚动消息传递到另一个文本框,以便它同步滚动.只有当其他文本框大小相同且行数相同时,这才真正有效.

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.

向您的项目添加一个新类并粘贴如下所示的代码.编译.将两个新控件从工具箱顶部拖放到表单上.将 Buddy 属性设置为两者上的另一个控件.运行,在它们两个中输入一些文本,然后在拖动滚动条时观察它们同步滚动.

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);
}

这篇关于如何同步两个多行文本框的滚动?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆