I have a Windows Forms textbox with background thread updating its value every second. If I place cursor inside textbox it will loose its current position at next update. Same thing with text selection.
I tried to solve it like that
protected void SetTextProgrammatically(string value)
{
// save current cursor position and selection
int start = textBox.SelectionStart;
int length = textBox.SelectionLength;
// update text
textBox.Text = value;
// restore cursor position and selection
textBox.SelectionStart = start;
textBox.SelectionLength = length;
}
It works good most of the time. Here is situation when it does not work:
1) I place cursor at the end of the text in textbox
2) press SHIFT and move cursor to the left using <- arrow key
Selection won't work properly.
It looks like combination SelectionStart=10
and SelectionLength=1
automatically moves cursor to position 11 (not 10 as I want it to be).
Please let me know if there is anything I can do about it! I am using Framework.NET 2.0.
There must be a way to set cursor position in textbox other then SelectionStart+SelectionLength
.
//save position
bool focused = textBox1.Focused;
int start = textBox1.SelectionStart;
int len = textBox1.SelectionLength;
//do your work
textBox1.Text = "duviubobioub";
//restore
textBox1.SelectionStart = start;
textBox1.SelectionLength = len ;
textBox1.Select();
I have found the solution!
// save current cursor position and selection
int start = textBox.SelectionStart;
int length = textBox.SelectionLength;
Point point = new Point();
User32.GetCaretPos(out point);
// update text
textBox.Text = value;
// restore cursor position and selection
textBox.Select(start, length);
User32.SetCaretPos(point.X, point.Y);
Now its working just like it should.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With