This article belongs to the author original, reproduced please specify, thank you
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, pick up
I come down here to provide a simple and quick way to achieve: RichTextBox scroll bar synchronization function.
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
1 Private intGetlinenovscroll (RichTextBox RTB)2 {3 //get current coordinate information4Point P =RTB. Location;5 intCrntfirstindex =RTB. Getcharindexfromposition (p);6 intCrntfirstline =RTB. Getlinefromcharindex (crntfirstindex);7 returnCrntfirstline;8}
Second method, quickly go to a row in the RichTextBox control
1 Private voidTrunrowsid (intIcoderowsid, RichTextBox RTB)2 {3 Try4 {5Rtb. SelectionStart =RTB. Getfirstcharindexfromline (ICODEROWSID);6Rtb. SelectionLength =0;7 RTB. Scrolltocaret ();8 }9 CatchTen { One A } -}
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.
1 Private void richtextbox1_vscroll (object sender, EventArgs e)2 {3 int crntlastline= getlinenovscroll (RichTextBox1, Panel1)-?; 4 Trunrowsid (Crntlastline, richTextBox2); 5 }
Finally, two scroll bars are synchronized.
If you find any other problems, please leave a message below. I just opened a blog soon, we learn from each other and grow together, thank you
C # Ultra-simple method to implement two RichTextBox control scroll bars synchronized scrolling