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

James May picture James May · Feb 8, 2009 · Viewed 95.1k times · Source

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

Answer

Matt Hamilton picture Matt Hamilton · Feb 8, 2009

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");