Reputation: 1329
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
.
Upvotes: 6
Views: 42311
Reputation: 21
To set the cursor position in textbox without selection start...!
textbox1.Select(textbox1.text.length,0); /* ===> End of the textbox */
textbox1.Select(0,0); /* ===> Start of the textbox */
Upvotes: 1
Reputation: 1329
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.
Upvotes: 4
Reputation: 4628
//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();
Upvotes: 4