Posted By

jimfred on 03/17/11


Tagged

RichTextBox


Versions (?)

Scroll multiple RichTextBoxes (or TextBoxes) in unison (synchronized scrolling).


 / Published in: C#
 

URL: /gist.github.com/593809

This is useful for WinForm apps with multiple TextBoxes that need to be scrolled in unison. Similar applications are diff GUIs that show 2 or more files side-by-side, where each window needs to be scrolled in unison.

The approach below is a simpler alternative to http://stackoverflow.com/questions/1827323/c-synchronize-scroll-position-of-two-richtextboxes

  1. /// Subclass RichTextBox to add the capability to bind scrolling for multiple RichTextBoxs.
  2. /// This is useful for 'parallel' RTBs that require synchronized scrolling.
  3. /// Taken from https://gist.github.com/593809
  4. /// Added WM_HSCROLL
  5. /// Added BindScroll() to form a two-way linkage between RichTextBoxes.
  6. /// Example usage showing how to bind 3 RichTextBoxes together:
  7. /// rtb1.BindScroll(rtb2);
  8. /// rtb2.BindScroll(rtb3);
  9. /// rtb3.BindScroll(rtb1);
  10. class RichTextBoxSynchronizedScroll : RichTextBox
  11. {
  12.  
  13. private const int WM_VSCROLL = 0x115;
  14. private const int WM_HSCROLL = 0x114;
  15.  
  16. private List<RichTextBoxSynchronizedScroll> peers = new List<RichTextBoxSynchronizedScroll>();
  17.  
  18. /// <summary>
  19. /// Establish a 2-way binding between RTBs for scrolling.
  20. /// </summary>
  21. /// <param name="arg">Another RTB</param>
  22. public void BindScroll( RichTextBoxSynchronizedScroll arg )
  23. {
  24. if ( peers.Contains( arg ) || arg==this ) { return; }
  25. peers.Add( arg );
  26. arg.BindScroll(this);
  27. }
  28.  
  29. private void DirectWndProc(ref Message m)
  30. {
  31. base.WndProc(ref m);
  32. }
  33.  
  34. protected override void WndProc(ref Message m)
  35. {
  36. if (m.Msg == WM_VSCROLL || m.Msg == WM_HSCROLL )
  37. {
  38. foreach (RichTextBoxSynchronizedScroll peer in this.peers)
  39. {
  40. Message peerMessage = Message.Create(peer.Handle, m.Msg, m.WParam, m.LParam);
  41. peer.DirectWndProc(ref peerMessage);
  42. }
  43. }
  44.  
  45. base.WndProc(ref m);
  46. }
  47. }

Report this snippet  

You need to login to post a comment.