将两个富文本框滚动在一起,我可以';我想不通
本文关键字:我可以 在一起 想不通 滚动 两个 文本 | 更新日期: 2023-09-27 18:25:22
当我向上滚动聊天框时,我想向上滚动timeBox。(不一定反之亦然)
我找到了以下代码来做到这一点:
/// Subclass RichTextBox to add the capability to bind scrolling for multiple RichTextBoxs.
/// This is useful for 'parallel' RTBs that require synchronized scrolling.
/// Taken from https://gist.github.com/593809
/// Added WM_HSCROLL
/// Added BindScroll() to form a two-way linkage between RichTextBoxes.
/// Example usage showing how to bind 3 RichTextBoxes together:
/// rtb1.BindScroll(rtb2);
/// rtb2.BindScroll(rtb3);
/// rtb3.BindScroll(rtb1);
class RichTextBoxSynchronizedScroll : RichTextBox
{
private const int WM_VSCROLL = 0x115;
private const int WM_HSCROLL = 0x114;
private List<RichTextBoxSynchronizedScroll> peers = new List<RichTextBoxSynchronizedScroll>();
/// <summary>
/// Establish a 2-way binding between RTBs for scrolling.
/// </summary>
/// <param name="arg">Another RTB</param>
public void BindScroll( RichTextBoxSynchronizedScroll arg )
{
if ( peers.Contains( arg ) || arg==this ) { return; }
peers.Add( arg );
arg.BindScroll(this);
}
private void DirectWndProc(ref Message m)
{
base.WndProc(ref m);
}
protected override void WndProc(ref Message m)
{
if (m.Msg == WM_VSCROLL || m.Msg == WM_HSCROLL )
{
foreach (RichTextBoxSynchronizedScroll peer in this.peers)
{
Message peerMessage = Message.Create(peer.Handle, m.Msg, m.WParam, m.LParam);
peer.DirectWndProc(ref peerMessage);
}
}
base.WndProc(ref m);
}
}
然而,我已经为此绞尽脑汁了两个多小时,试图让不同的代码发挥作用,但我无法让它们中的任何一个发挥作用,因为我只是相对地才开始编程,我不知道该如何处理这些代码。
我试着把它作为一个额外的类放在表单的代码中,但后来我无法将BindScroll()应用于任何文本框,因为我无法引用它们或实例。
也许我可以,但我不知道怎么做。我尝试过只在类内部使用代码,而不将其本身作为类,但这导致了错误。
任何帮助都将不胜感激。。。
测试代码后,它似乎可以正常工作。你的问题可能是你不知道如何使用代码,你必须将新的richtextbox声明为RichTextBoxSynchronizedScroll
,而不是标准的RichTextBox
:
//Here is the test
public partial class Form1 : Form {
public Form1(){
InitializeComponent();
rb1.Size = new Size(200,100);
rb2.Size = rb1.Size;
rb2.Left = rb1.Right + 5;
rb1.Parent = rb2.Parent = this;
rtb1.BindScroll(rtb2);
//try populating some data for both the richtextboxes
for(int i = 0; i < 200; i++)
rtb1.Text += Guid.NewGuid() + "'r'n";
rtb2.Text = rtb1;
//now try scrolling the rtb1
//I suggest you should add WM_MOUSEWHEEL = 0x20a into the if statement
//something like this: if (m.Msg == WM_VSCROLL || m.Msg == WM_HSCROLL || m.Msg == WM_MOUSEWHEEL) ...
}
RichTextBoxSynchronizedScroll rtb1 = new RichTextBoxSynchronizedScroll();
RichTextBoxSynchronizedScroll rtb2 = new RichTextBoxSynchronizedScroll();
}
//That's all
我已经解决了整整3个小时。。。我想要一些非常简单的东西。我考虑了滚动的各个方面。您只需要创建VScrollBar并定义类似的滚动事件
private void vScrollBar1_Scroll(object sender, ScrollEventArgs e)
{
int position = text1.GetFirstCharIndexFromLine(vScrollBar1.Value);
//position only 0.character on line
textBox1.Select(position, 0);//if position=vScrollBar1.Value you would actually scrolling char by char
textBox2.Select(position, 0);
textBox1.ScrollToCaret();
textBox2.ScrollToCaret();
}
希望我将来能找到这个。