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

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

问题描述

我如何可以同步2多行文本框的滚动在C#(的WinForms)?

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?

推荐答案

是的,你必须创建一个自定义文本框,所以你可以检测到它滚动。关键是要通过滚动消息到其他的文本框,因此将同步滚动。当其他的文本框是大约相同的尺寸,并且具有相同数目的行这确实仅效果很好。

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.

添加一个新类到您的项目并粘贴如下所示的code。编译。放下两人从工具箱顶部的新控件到窗体。该好友属性设置为同时在其他控制。奔跑中,他们两人键入一些文字和观看他们滚动同步在拖动滚动条。

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

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

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