Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I find the position of a cursor in a text box? C#

People also ask

How do I find the cursor position in text area?

If there is no selection, you can use the properties . selectionStart or . selectionEnd (with no selection they're equal). var cursorPosition = $('#myTextarea').

How do I set the cursor position in input?

To move the cursor to the end of an input field: Use the setSelectionRange() method to set the current text selection position to the end of the input field. Call the focus() method on the input element. The focus method will move the cursor to the end of the input element's value.

How do you move the cursor to the end of the text in a TextBox C#?

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 move the cursor out of the TextBox?

If you select Built-in text box, left-click the text box you want to use, and it will appear in the document. If you select Draw Text Box, a crosshair cursor will appear. Left-click your mouse and while holding it down, drag your mouse until the text box is the desired size.


Regardless of whether any text is selected, the SelectionStart property represents the index into the text where you caret sits. So you can use String.Insert to inject some text, like this:

myTextBox.Text = myTextBox.Text.Insert(myTextBox.SelectionStart, "Hello world");

You want to check the SelectionStart property of the TextBox.


James, it's pretty inefficient that you need to replace the whole string when you only want to insert some text at the cursor position.

A better solution would be:

textBoxSt1.SelectedText = ComboBoxWildCard.SelectedItem.ToString();

When you have nothing selected, that will insert the new text at the cursor position. If you have something selected, this will replace your selected text with the text you want to insert.

I found this solution from the eggheadcafe site.


All you have to do is this:

Double click the item (button, label, whatever) that will insert text into the document at the cursor. Then type this in:

richTextBox.SelectedText = "whatevertextyouwantinserted";

Here is my working realization, alowing to type only digits, with restoring last valid typing text position:

Xaml:

<TextBox
      Name="myTextBox" 
      TextChanged="OnMyTextBoxTyping" />

Code behind:

private void OnMyTextBoxTyping(object sender, EventArgs e)
{
    if (!System.Text.RegularExpressions.Regex.IsMatch(myTextBox.Text, @"^[0-9]+$"))
    {
        var currentPosition = myTextBox.SelectionStart;
        myTextBox.Text = new string(myTextBox.Text.Where(c => (char.IsDigit(c))).ToArray());
        myTextBox.SelectionStart = currentPosition > 0 ? currentPosition - 1 : currentPosition;
    }
}