1

I have a textbox (textBox1 as an example) to which i'm periodically appending a character (every second or so). I wish to make it so that when the text gets too long to fit in the textbox the overflow will actually go towards the left of the textbox even when it's not focused instead of the normal behaviour which is to the right, this way the last character will always be shown. The way I've done it is when I'm adding the character i'm also doing:

textBox1.ScrollToHorizontalOffset(textBox1.GetRectFromCharacterIndex(textBox1.Text.Length).Right);

This works nicely until the length of the text gets long enough. After this point scrolling will just stop and the current left overflow will remain, but new overflow will go to the right of the textbox. For testing I'm writing the current text's length and textBox1.GetRectFromCharacterIndex(textBox1.Text.Length).Right to console on every update:

...
Length: 22
Rect.Right: 81.99
Length: 23
Rect.Right: 85.4
Length: 24
Rect.Right: 88.81
Length: 25
Rect.Right: 91.41
Length: 26
Rect.Right: 91.41
Length: 27
Rect.Right: 91.4099999999999
Length: 28
Rect.Right: 91.4099999999999
Length: 29
Rect.Right: 91.4099999999999
Length: 30
Rect.Right: 91.4099999999999
...
Length: 47
Rect.Right: 91.4099999999999
Length: 48
Rect.Right: 91.4099999999999
Length: 49
Rect.Right: 91.4099999999999
Length: 50
Rect.Right: 91.4099999999999
Length: 51
Rect.Right: 91.4099999999999
Length: 52
Rect.Right: 92.88
Length: 53
Rect.Right: 94.8199999999999
Length: 54
Rect.Right: 96.29
Length: 55
Rect.Right: 98.2299999999999
Length: 56
Rect.Right: 99.7
Length: 57
Rect.Right: 101.64

Before Text.Length is 25 the textbox is still wide enough to fit everything. After this point the text doesn't fit anymore and the scrolling works up until the length is 52.

rhyek
  • 1,790
  • 1
  • 19
  • 23

2 Answers2

3

That behaviour is odd -- I reproduced the same.

I got the effect for which you are looking by instead using

textbox1.ScrollToHorizontalOffset(double.MaxValue);

Since you want to scroll all the way right, there is no harm in passing a value greater than the actual location of the character.

Jay
  • 56,361
  • 10
  • 99
  • 123
0

All of the above did not work reliably for me. While doing something else, I stumbled across this approach (using selection highlight). TB is the TextBox, ofs is the character index for the desired offset.

TB.Focus();   //must be used
TB.HorizontalContentAlignment = System.Windows.HorizontalAlignment.Right;
TB.HorizontalContentAlignment = System.Windows.HorizontalAlignment.Left;
TB.Select(0, ofs);   //select up through desired offset
TB.Select(0, 0);     //turn off selection

...hope this helps!

We B Martians
  • 367
  • 2
  • 12