Azri Hafiz
Azri Hafiz

Reputation: 35

Adding text between sentence in RTB

My Code:

private void richTextBox1_KeyDown(object sender, KeyEventArgs e)
    {
        if (e.Control && e.KeyCode == Keys.Q)
        {
            richTextBox1.Text = richTextBox1.Text + "this is a text";
        }
    }

My problem is whenever I press CTRL + Q, the text will be added at the end of the sentence but not where the IBeam is. I want it to be added at where the IBeam is. I don't know how to make the text be added at where the IBeam is. I hope you guys understand.

Thanks in advance!

Upvotes: 1

Views: 134

Answers (1)

Mike Perrenoud
Mike Perrenoud

Reputation: 67898

That's because you're actually appending the text. The behavior would be expected. However, if you insert the text, you'll get what you want:

richTextBox1.Text = richTextBox1.Text.Insert(
    richTextBox1.SelectionStart,
    "this is a text");

Take note to the documentation of SelectionStart, it states:

If no text is selected in the control, this property indicates the insertion point, or caret, for new text.

Upvotes: 2

Related Questions