In Visual C#.NET:
How do I add/append text directly to where the user's cursor is in a Rich Text Box?
For example, if the user clicked a button, and their cursor was somewhere in the rich text box, text would be immediately added to the location of their cursor.
To position the cursor at the beginning of the contents of a TextBox control, call the Select method and specify the selection start position of 0, and a selection length of 0.
Under Insert controls, click Rich Text Box. In the Rich Text Box Binding dialog box, select the field in which you want to store rich text box data, and then click OK.
First, get the current position of cursor with the help of property named as selectionStart on textarea/inputbox. To insert the text at the given position we will use slice function to break the string into two parts and then we will append both parts to the text(text_to_insert) in front and end of the text.
Use the SelectedText
property:
textBox.SelectedText = "New text";
This will overwrite any selected text they have though. If you don't want that you can first set the SelectionLength
property to 0:
textBox.SelectionLength = 0;
textBox.SelectedText = "New text";
rtb.SelectionStart += rtb.SelectionLength;
rtb.SelectionLength = 0;
rtb.SelectedText = "asdf";
This moves the cursor just past the end of the current selection, then adds "asdf" at the end.
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