The purpose of all the calculations presented below is: to determine the maximum scroll value of the RichTextBox for working with the custom scrollbar.
Useful materials / tips:
- To find out the value that the standard scrollbar receives while scrolling, use the Microsoft Spy++ program;
- Absolute Difference Calculator: https://calculatorpack.com/absolute-difference-calculator.
Determine the maximum vertical scroll value:
NOTE: (code works correctly if you don't scale the RichTextBox contents).
private void DetermineVMax(RichTextBox RTB) {
// Y position of the first character
int y1 = RTB.GetPositionFromCharIndex(0).Y;
// Y position of the last character
int y2 = RTB.GetPositionFromCharIndex(RTB.TextLength).Y;
// First option: The height of the line - returns 43
double heightLine = Math.Ceiling(RTB.Font.GetHeight());
// Second option: The height of the line - returns 45
// NOTE: GetFirstCharIndexFromLine( NUMBER )
// 0 is the first line, 1 is the second line, etc.
//int index = targetCtrl.GetFirstCharIndexFromLine(1);
//int heightLine = targetCtrl.GetPositionFromCharIndex(index).Y;
// Absolute difference between the position of the 1st and the last characters
int absoluteDifference = Math.Abs(y1 - y2);
// RichTextBox height
int heightRtb = RTB.ClientSize.Height;
// Maximum vertical scroll value
// NOTE: if you don't add a line height, the RTB content will not be displayed in full
int max = absoluteDifference - heightRtb + (int)heightLine;
}
Thanks to the stack overflow response (Size RichTextBox according to contents), a another solution was found for calculating the maximum value of vertical / horizontal scrolling (taking into account the scaling inside the RichTextBox).
Order of actions
- Sign the RichTextBox to "ContentsResized" and "Resize" events;
- Use the code below.
Determine the maximum vertical scroll value:
int heightContentRtb, widthContentRtb;
private void DetermineVMax(RichTextBox RTB) {
int heightContainerRtb = RTB.ClientSize.Height;
int max = heightContentRtb - heightContainerRtb + 1;
}
Determine the maximum horizontal scroll value:
private void DetermineHMax(RichTextBox RTB) {
int widthContainerRtb = RTB.ClientSize.Width;
int max = widthContentRtb - widthContainerRtb + 1;
}
Code inside the "ContentsResized" and "Resize" events
private void richTextBox1_ContentsResized(object sender, ContentsResizedEventArgs e) {
//heightContentRtb = e.NewRectangle.Height; DetermineVMax(richTextBox1);
widthContentRtb = e.NewRectangle.Width; DetermineHMax(richTextBox1);
}
private void richTextBox1_Resize(object sender, EventArgs e) {
//DetermineVMax(richTextBox1);
DetermineHMax(richTextBox1);
}