Reputation: 105
There is a RichTextBox with scrollbars disabled. Tried to find out the maximum scroll value, using:
float heightLine = targetCtrl.Font.GetHeight() / 3; Maximum = (int)Math.Ceiling(targetCtrl.GetPreferredSize(targetCtrl.Size).Height - targetCtrl.Height + heightLine);
- at the beginning the maximum is correct, but as you add or change the size of the elements you get a value that is smaller than the real maximum.Upvotes: 0
Views: 697
Reputation: 105
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:
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
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);
}
Upvotes: 2