I want to get the current cursor position from a WPF TextBox. If a TextBox
contains text abhishek
and cursor is blinking after abhi
then i want that index, so that later after clearing the TextBox
programmatically and assigning some other or same text programmatically I want to make the cursor blink just after 4 characters.
I have tried get cursor position like this,
_tempFuncName = txtFunctionName.Text;
_cursorPosition = txtFunctionName.SelectionStart;
_selectionLength = txtFunctionName.SelectionLength;
And set back at some later stage from other event like this,
txtFunctionName.Text = _tempFuncName;
txtFunctionName.SelectionStart = _cursorPosition;
txtFunctionName.SelectionLength = _selectionLength;
Here underscore variables are page level variables.
This code is not working. Is there some other approach?
To position the cursor at the end of the contents of a TextBox control, call the Select method and specify the selection start position equal to the length of the text content, and a selection length of 0.
SetCursorPosition(Int32, Int32) Method is used to set the position of cursor. Basically, it specifies where the next write operation will begin in the console window.
The cursor position is represented by the line number and the character number and signifies where the next character will be displayed. For example, cursor position 1,1 always indicates the upper-leftmost corner position on the terminal. Cursor position 10,30 indicates the 30th character position on the 10th line.
You can play with caretindex property of a text box
//You can set this property on some event
NumberOfDigits.CaretIndex = textbox.Text.Length;
You just need to add one line to set focus on textbox otherwise everything is working fine.
txtFunctionName.Text = _tempFuncName;
txtFunctionName.SelectionStart = _cursorPosition;
txtFunctionName.SelectionLength = _selectionLength ;
txtFunctionName.Focus();
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