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?
相关问题
- Sorting 3 numbers without branching [closed]
- Graphics.DrawImage() - Throws out of memory except
- Generic Generics in Managed C++
- Why am I getting UnauthorizedAccessException on th
- 求获取指定qq 资料的方法
I did this for a small project a while ago, and here's the simplist solution I found.
Create a new control by subclassing RichTextBox:
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:
I think this code has problems if all the 'linked' controls don't have the same number of displayable lines.
A variation of Jay's subclass approach can be found in Joseph Kingry's post here: Synchronizing Multiline Textbox Positions in C#. Joseph's approach also subclasses but doesn't require a _VScroll event handler. I used that approach to do a 3-way bind between 3 boxes and added WM_HSCROLL.
[Visual Studio C# 2010 Express, v10.0.30319 on a Windows 7 64bit installation]
I've used Donut's solution posted above, but found a problem when scrolling to the end of RichTextBoxes that contain many lines.
If the result of
GetScrollPos()
is>0x7FFF
then whennPos
is shifted, the top bit is set. The creation of theIntPtr
with the resultingwParam
variable will then fail with anOverflowException
. You can easily test this with the following (the second line will fail):A version of
SendMessage()
that usesUIntPtr
would appear to be a solution, but I couldn't get that to work. So, I've use the following:This should be good up to
0xffff
, but would fail after that. I've not yet experienced a>0xffff
result fromGetScrollPos()
, and assume that User32.dll is unlikely to have a 64bit version ofSendCommand()
, but any solutions to that problem would be greatly appreciated.Thanks Jay for your answer; after some more searching I also found the method described here. I'll outline it below for anyone else interested.
First, declare the following enums:
Next, add external references to
GetScrollPos
andSendMessage
.Finally, add an event handler for the
VScroll
event of the appropriateRichTextBox
:In this case,
richTextBox2
's vertical scroll position will be synchronized withrichTextBox1
.