同步两个 RichTextBox 的滚动位置? [英] Synchronize Scroll Position of two RichTextBoxes?

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

问题描述

在我的应用程序表单中,我有两个 RichTextBox 对象.它们都将始终具有相同的文本行数.我想同步"这两者之间的垂直滚动,以便当用户更改一个的垂直滚动位置时,另一个滚动相同的数量.我该怎么做?

In my application's form, I have two RichTextBox objects. They will both always have the same number of lines of text. I would like to "synchronize" the vertical scrolling between these two, so that when the user changes the vertical scroll position on one, the other scrolls the same amount. How might I go about doing this?

推荐答案

我不久前为一个小项目做过这个,这是我找到的最简单的解决方案.

I did this for a small project a while ago, and here's the simplist solution I found.

通过继承 RichTextBox 创建一个新控件:

Create a new control by subclassing RichTextBox:

   public class SynchronizedScrollRichTextBox : System.Windows.Forms.RichTextBox
    {
        public event vScrollEventHandler vScroll;
        public delegate void vScrollEventHandler(System.Windows.Forms.Message message);

        public const int WM_VSCROLL = 0x115;

        protected override void WndProc(ref System.Windows.Forms.Message msg) {
            if (msg.Msg == WM_VSCROLL) {
                if (vScroll != null) {
                    vScroll(msg);
                }
            }
            base.WndProc(ref msg);
        }

        public void PubWndProc(ref System.Windows.Forms.Message msg) {
            base.WndProc(ref msg);
        }
    }     

将新控件添加到表单中,并为每个控件显式通知控件的其他实例其 vScroll 位置已更改.像这样:

Add the new control to your form and for each control explicitly notify the other instances of the control that its vScroll position has changed. Somthing like this:

private void scrollSyncTxtBox1_vScroll(Message msg) {
    msg.HWnd = scrollSyncTxtBox2.Handle;
    scrollSyncTxtBox2.PubWndProc(ref msg);
}

如果所有链接"控件的可显示行数不同,我认为此代码有问题.

I think this code has problems if all the 'linked' controls don't have the same number of displayable lines.

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

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