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

9

63

I have a standard WinForms TextBox and I want to insert text at the cursor's position in the text. How can I get the cursor's position?

Thanks

Marsupial answered 8/2, 2009 at 22:33 Comment(2)
do you need position at the all screen, or at the form?Gatefold
Could you read me last post below? ThanksMarsupial
N
95

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");
Neustria answered 8/2, 2009 at 22:38 Comment(3)
This is great, but if you press the enter key the SelectionStart increments by 2. Any idea why?Metamerism
Probably because a new line (at least on Windows) is a combination of char 10 and char 13 - new line and carriage return.Neustria
Oh! Thank you :DMetamerism
H
16

You want to check the SelectionStart property of the TextBox.

Hardshell answered 8/2, 2009 at 22:36 Comment(0)
C
8

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.

Columbian answered 16/4, 2009 at 23:10 Comment(0)
A
5

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";
Astrict answered 5/9, 2011 at 13:54 Comment(1)
Duplicate of this answer from two years earlierInstalment
B
4

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;
    }
}
Beamy answered 25/9, 2014 at 4:53 Comment(1)
Perfect. It can't be more concise.Asterisk
L
2

You have to keep the SelectionStart property in a variable, and then when you press the button, shift the focus back to the TextBox. Then set the SelectionStart property to the one in the variable.

Liegnitz answered 8/2, 2009 at 22:56 Comment(0)
M
2

On what event would you suggest I record the variable? Leave?

Currently I have:

private void comboBoxWildCard_SelectedIndexChanged(object sender, EventArgs e)
{
    textBoxSt1.Focus();
    textBoxSt1.Text.Insert(intCursorPos, comboBoxWildCard.SelectedItem.ToString());

}

private void textBoxSt1_Leave(object sender, EventArgs e)
{
    intCursorPos = textBoxSt1.SelectionStart;
}

Recording on the Leave event is working but the text doesn't get inserted, am I missing something?

UPDATE: I needed textBoxSt1.Text =

textBoxSt1.Text = textBoxSt1.Text.Insert(intCursorPos, comboBoxWildCard.SelectedItem.ToString());

Thanks all.

Thanks

Marsupial answered 8/2, 2009 at 22:58 Comment(0)
F
2

To get the caret position when you click the mouse within the text of a TextBox, use the TextBox MouseDown event. Create a point using X and Y properties of the MouseEventArgs. The TextBox has a method called GetCharIndexFromPosition(point). Pass it the point and it returns the caret position. This works if you are using the mouse to determine where you want to insert the new text.

Fumble answered 19/5, 2014 at 0:19 Comment(2)
-1: The original question makes no mention of needing the cursor position in response to a mouse event, and the question was answered and accepted in 2009.Thaddeusthaddus
Ha ha... this is a bit funny. The question actually asked about the position of the cursor, so this is sort of a good answer. It's pretty clear that the question was actually wanting the position of the caret rather than the cursor, but that's not what they asked for.Bologna
L
1
int cursorPosition = textBox1.SelectionStart;
//it will extract your current cursor position where ever it is
//textBox1 is name of your text box. you can use one
//which is being used by you in your form
Lesbianism answered 9/4, 2013 at 9:37 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.