This article mainly introduces the C # implementation of the two RichTextBox control scroll bar synchronization scrolling Simple method, the article introduced in very detailed, for everyone has a certain reference learning value, the need for friends below to see it together.
Objective
Sometimes we need to implement a control article and so on, often put the text into two RichTextBox controls, but if we need to synchronize scrolling view, to achieve better viewing results.
Of course, a traditional method of overloading a control or a custom control can do the same thing, but it is cumbersome for newbies or people who want to use the control only once. So, let me give you a quick and easy way to do this: RichTextBox the scroll bar synchronization function.
Here's how:
First, we create two RichTextBox controls in the WinForm form
Here are two methods that I often use to
The first method, gets the line number in the RichTextBox control where the current mouse is located
private int Getlinenovscroll (RichTextBox RTB) { //get current coordinate information point p = RTB. Location; int crntfirstindex = RTB. Getcharindexfromposition (p); int crntfirstline = RTB. Getlinefromcharindex (crntfirstindex); return crntfirstline; }
Second method, quickly go to a row in the RichTextBox control
private void Trunrowsid (int icoderowsid, RichTextBox RTB) { try { RTB. SelectionStart = RTB. Getfirstcharindexfromline (ICODEROWSID); Rtb. selectionlength = 0; Rtb. Scrolltocaret (); } Catch { } }
With these two methods, we can implement the function of scroll bar synchronization.
The idea is as follows: First, when the richTextBox1 scrolling, through the Getlinenovscroll method, get the richTextBox1 mouse corresponding line number. And then
By the Trunrowsid method, the obtained Richtexbox1 line number is positioned in richtextbox2 to achieve RichTextBox2 followed Richtexbox1
scroll bar scroll together;
Add the following code to the VScroll event in RichTextBox1, notice that I have one here? , which represents an offset, possibly because of layout reasons (such as control size, etc.)
resulting in two RichTextBox different steps, generally write 0 can be, if the gap is too large, adjust the value of their own.
private void Richtextbox1_vscroll (object sender, EventArgs e) { int crntlastline= getlinenovscroll ( RichTextBox1, Panel1)-?; Trunrowsid (Crntlastline, RichTextBox2); }
Finally, two scroll bars are synchronized.
Summarize