Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to get and set current cursor position of WPF textbox

Tags:

c#

.net

wpf

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?

like image 206
Abhi Avatar asked Oct 13 '11 07:10

Abhi


People also ask

How to change cursor position in TextBox?

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.

How do I change cursor position?

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.

What is the position of cursor?

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.


2 Answers

You can play with caretindex property of a text box

//You can set this property on some event
NumberOfDigits.CaretIndex = textbox.Text.Length;
like image 143
sobby01 Avatar answered Oct 07 '22 15:10

sobby01


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();
like image 39
Upendra Chaudhari Avatar answered Oct 07 '22 14:10

Upendra Chaudhari